2024-04-27 04:01:59 发布
网友
data = { 'ids': [12, 3, 4, 5, 6 , ...] } urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data))
我想发送一个POST请求,但是其中一个字段应该是一个数字列表。我该怎么做?(JSON?)
对于python 3.4.2,我发现以下方法可以工作:
import urllib.request import json body = {'ids': [12, 14, 50]} myurl = "http://www.testmycode.com" req = urllib.request.Request(myurl) req.add_header('Content-Type', 'application/json; charset=utf-8') jsondata = json.dumps(body) jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes req.add_header('Content-Length', len(jsondataasbytes)) print (jsondataasbytes) response = urllib.request.urlopen(req, jsondataasbytes)
如果您的服务器希望POST请求是json,那么您需要添加一个头,并序列化请求的数据。。。
Python2.x
import json import urllib2 data = { 'ids': [12, 3, 4, 5, 6] } req = urllib2.Request('http://example.com/api/posts/create') req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(data))
Python3.x
https://stackoverflow.com/a/26876308/496445
如果不指定头,它将是默认的application/x-www-form-urlencoded类型。
application/x-www-form-urlencoded
我建议使用难以置信的requests模块。
requests
http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(payload), headers=headers)
对于python 3.4.2,我发现以下方法可以工作:
如果您的服务器希望POST请求是json,那么您需要添加一个头,并序列化请求的数据。。。
Python2.x
Python3.x
https://stackoverflow.com/a/26876308/496445
如果不指定头,它将是默认的
application/x-www-form-urlencoded
类型。我建议使用难以置信的
requests
模块。http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers
相关问题 更多 >
编程相关推荐