How do I send a POST request as a JSON?

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

I want to send a POST request, but one of the fields should be a list of numbers. How can I do that? (JSON?)

351105 次浏览

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

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://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)

You have to add header,or you will get http 400 error. 该代码在 python2.6,centos5.4上运行良好

密码:

    import urllib2,json


url = 'http://www.google.com/someservice'
postdata = {'key':'value'}


req = urllib2.Request(url)
req.add_header('Content-Type','application/json')
data = json.dumps(postdata)


response = urllib2.urlopen(req,data)

For python 3.4.2, I found the following will work:

import urllib.request
import json


body = {'ids': [12, 14, 50]}
myurl = "http://www.testmycode.example"


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))
response = urllib.request.urlopen(req, jsondataasbytes)

如果 URL 包含 Query String/Parameter 值,那么这对于 Python 3.5非常有效,

请求 URL = https://bah2.example/ws/rest/v1/concept/ 参数值 = 21f6bb43-98a1-419d-8f0c-8133669e40ca

import requests


url = 'https://bahbah2.example/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), json=data)
print(r.status_code)

下面是如何使用 Python 标准库中的 urllib.request 对象的示例。

import urllib.request
import json
from pprint import pprint


url = "https://app.close.com/hackwithus/3d63efa04a08a9e0/"


values = {
"first_name": "Vlad",
"last_name": "Bezden",
"urls": [
"https://twitter.com/VladBezden",
"https://github.com/vlad-bezden",
],
}




headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}


data = json.dumps(values).encode("utf-8")
pprint(data)


try:
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as f:
res = f.read()
pprint(res.decode())
except Exception as e:
pprint(e)

在最新的请求包中,您可以使用 requests.post()方法中的 json参数来发送一个 json 结果,头中的 Content-Type将被设置为 application/json。不需要显式指定标头。

import requests


payload = {'key': 'value'}
requests.post(url, json=payload)

这个对我来说很适合

import requests


data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)

这里许多答案中使用的 请求软件包很棒,但是没有必要。您可以使用 Python 3标准库一步完成 JSON 数据的 POST:

import json
from urllib import request


request.urlopen(request.Request(
'https://example.com/url',
headers={'Content-Type': 'application/json'},
data=json.dumps({
'pi': 3.14159
}).encode()
))

如果需要读取结果,可以从返回的类似文件的对象中读取 .read(),并使用 json.loads()对 JSON 响应进行解码。