使用urllib2发起带头的POST请求
我想要向一个网址发送一个带有特定数据和头信息的POST请求。我通过这两个链接找到了方法,但它并没有成功:
https://stackoverflow.com/questions/5693931/python-post-request
如何在HTTP请求中使用urllib2发送自定义头信息?
这是我的代码:
import urllib
import urllib2
url = 'https://clients6.google.com/rpc'
values = [
{"method": "pos.plusones.get",
"id": "p",
"params": {
"nolog": True,
"id": "http://www.newswhip.com",
"source": "widget",
"userId": "@viewer",
"groupId": "@self"
},
"jsonrpc": "2.0",
"key": "p",
"apiVersion": "v1"
}]
headers = {"Content-type" : "application/json:"}
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
print the_page
我可以在Postman这个工具中用这些值得到结果。但是执行这段代码后,结果是:
Traceback (most recent call last):
File "D:/Developer Center/Republishan/republishan2/republishan2/test2.py", line 22, in <module>
data = urllib.urlencode(values)
File "C:\Python27\lib\urllib.py", line 1312, in urlencode
raise TypeError
TypeError: not a valid non-string sequence or mapping object
我还尝试用字典代替列表,像这样:
values = {"method": "pos.plusones.get",
"id": "p",
"params": {
"nolog": True,
"id": "http://www.newswhip.com",
"source": "widget",
"userId": "@viewer",
"groupId": "@self"
},
"jsonrpc": "2.0",
"key": "p",
"apiVersion": "v1"
}
这个脚本可以执行,但结果却出现了错误:
{"error":{"code":-32700,"message":"Unable to parse json","data":[{"domain":"global","reason":"parseError","message":"Unable to parse json"}]}}
正如我所说,我可以在Postman中用列表执行脚本,而不是字典。看看Postman中的结果:

1 个回答
4
看起来 urllib.urlencode 这个工具不太懂嵌套的字典:
In [38]: urllib.urlencode({"a": "asas", "df": {"sds": 123, "t": "fgfg"}})
Out[38]: 'a=asas&df=%7B%27t%27%3A+%27fgfg%27%2C+%27sds%27%3A+123%7D'
或者你的例子:
In [41]: urllib.urlencode(values)
Out[41]: 'jsonrpc=2.0&apiVersion=v1&id=p¶ms=%7B%27nolog%27%3A+True%2C+%27source%27%3A+%27widget%27%2C+%27userId%27%3A+%27%40viewer%27%2C+%27id%27%3A+%27http%3A%2F%2Fwww.newswhip.com%27%2C+%27groupId%27%3A+%27%40self%27%7D&key=p&method=pos.plusones.get'
你看,“params”里的大括号搞得乱七八糟的。
我不太确定怎么用 urllib 来解决这个问题。所以我推荐使用 requests 这个库。http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers
简单来说,它看起来会是这样的(你需要先安装 requests 库,比如用 pip:pip install requests
):
import requests
import json
url = 'https://clients6.google.com/rpc'
values = {
"method": "pos.plusones.get",
"id": "p",
"params": {
"nolog": True,
"id": "http://www.newswhip.com",
"source": "widget",
"userId": "@viewer",
"groupId": "@self"
},
"jsonrpc": "2.0",
"key": "p",
"apiVersion": "v1"
}
headers = {"content-type" : "application/json"}
req = requests.post(url, data=json.dumps(values), headers=headers)
print req.text
对我来说是有效的。