gpt4 book ai didi

python - 如何使用 urllib 将参数添加到 POST 请求正文?

转载 作者:行者123 更新时间:2023-11-30 22:20:28 29 4
gpt4 key购买 nike

我需要使用 urllib 发送以下格式的 POST 请求:

POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.twitter.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded

oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY

对于标题,我这样添加:

AccessRequest = urllib.request.Request('https://api.twitter.com/oauth/access_token')
AccessRequest.add_header('Authorization', oauth_header)

添加应保留在正文中的参数的正确方法是什么?

现在我正在做:

values = {
'oauth_verifier': verifier
}
data = urllib.parse.urlencode(values).encode('ascii')
resp = urllib.request.urlopen(AccessRequest, data=data)

但是肯定有什么问题,因为服务器返回了 HTTP 错误 401:需要授权。我做错了什么?

最佳答案

from urllib import request, parse
data = parse.urlencode({"data":"Hello Word?"}).encode()
req = request.Request("http://www.naver.com", data=data) # this will make the method "POST"
resp = request.urlopen(req)

如果运行此代码,数据包如下所示。

POST / HTTP/1.1
Accept-Encoding: identity
Host: www.naver.com
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 18
User-Agent: Python-urllib/3.4

data=Hello+Word%3F

如果我将 data = parse.urlencode({"data":"Hello Word?"}).encode() 更改为 data = parse.urlencode({"oauth_verifier": “uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY”}).encode()

数据包看起来像这样

POST / HTTP/1.1
Accept-Encoding: identity
Host: www.naver.com
Content-Type: application/x-www-form-urlencoded
Connection: close
Content-Length: 57
User-Agent: Python-urllib/3.4

oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY

这不是你想要的吗?

关于python - 如何使用 urllib 将参数添加到 POST 请求正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841889/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com