如何将POST请求作为JSON发送?

2024-04-27 04:01:59 发布

您现在位置:Python中文网/ 问答频道 /正文

data = {
        'ids': [12, 3, 4, 5, 6 , ...]
    }
    urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data))

我想发送一个POST请求,但是其中一个字段应该是一个数字列表。我该怎么做?(JSON?)


Tags: comapiidshttp列表datacreate数字
3条回答

对于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类型。

我建议使用难以置信的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)

相关问题 更多 >