Python urllib2 和 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3290522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
urllib2 and json
提问by pup
can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?
谁能指出一个教程,该教程向我展示了如何使用 urllib2 使用 JSON 格式的数据执行 POST 请求?
回答by Messa
Example - sending some data encoded as JSON as a POST data:
示例 - 将一些编码为 JSON 的数据作为 POST 数据发送:
import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()
回答by Stan
You certainly want to hack the header to have a proper Ajax Request :
您当然想破解标题以获得正确的 Ajax 请求:
headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()
And to json.loads the POST on the server-side.
并在服务器端 json.loads POST。
Edit : By the way, you have to urllib.urlencode(mydata_dict)before sending them. If you don't, the POST won't be what the server expect
编辑:顺便说一下,你必须urllib.urlencode(mydata_dict)在发送它们之前。如果不这样做,POST 将不会是服务器所期望的
回答by Bob Van Zant
Messa's answer only works if the server isn't bothering to check the content-type header. You'll need to specify a content-type header if you want it to really work. Here's Messa's answer modified to include a content-type header:
Messa 的答案仅在服务器不费心检查内容类型标头时才有效。如果您希望它真正起作用,则需要指定一个内容类型标头。这是 Messa 的答案修改为包含内容类型标头:
import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
回答by CloudMarc
Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.
无论 urllib 使用什么来计算 Content-Length 似乎都被 json 弄糊涂了,所以你必须自己计算。
import json
import urllib2
data = json.dumps([1, 2, 3])
clen = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()
Took me for ever to figure this out, so I hope it helps someone else.
让我永远弄明白了这一点,所以我希望它可以帮助别人。
回答by eseceve
To read json response use json.loads(). Here is the sample.
要读取 json 响应,请使用json.loads(). 这是示例。
import json
import urllib
import urllib2
post_params = {
'foo' : bar
}
params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())
回答by arcana
This is what worked for me:
这对我有用:
import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)

