如何使用urllib向POST请求的正文添加参数?

时间:2018-02-17 13:36:13

标签: python python-3.x urllib

我需要使用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:需要授权,因此必定存在问题。我做错了什么?

1 个答案:

答案 0 :(得分:1)

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

这不是你想要的吗?