小编典典

如何以JSON格式发送POST请求?

json

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

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


阅读 818

收藏
2020-07-27

共1个答案

小编典典

如果您的服务器期望POST请求为json,则您需要添加标头,并为请求序列化数据…

Python 2.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))

Python 3.x


如果不指定标题,它将是默认application/x-www-form-urlencoded类型。

2020-07-27