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

data = {

‘ids’: [12, 3, 4, 5, 6 , …]

}

urllib2.urlopen("http://abc.com/api/posts/create”,urllib.urlencode(data))

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

回答:

如果您的服务器期望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类型。

以上是 如何以JSON格式发送POST请求? 的全部内容, 来源链接: utcz.com/qa/427004.html

回到顶部