且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 08:26:46

如果您的服务器期望 POST 请求是 json,那么您需要添加一个标头,并序列化您的请求的数据...

If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...

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

https://***.com/a/26876308/496445

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

If you don't specify the header, it will be the default application/x-www-form-urlencoded type.