[英]Using urllib2 to make a post request with headers
我想將帖子請求發送到具有特定數據和標題類型的URL。 使用這兩個鏈接,我發現如何做到這一點,但它不起作用:
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 Rest Client中獲得帶有這些值的結果。 但執行此代碼后,結果是:
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 Rest Client用list而不是字典來執行腳本。 看看Postman的結果: 我該怎么辦?
看起來urllib.urlencode不了解嵌套的dicts:
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來解決這個問題。 所以我會推薦請求庫。 http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers
簡而言之,它看起來像這樣(你需要先安裝請求庫,例如使用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
這個對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.