问题:如何以JSON格式发送POST请求?
data = {
'ids': [12, 3, 4, 5, 6 , ...]
}
urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data))
我想发送POST请求,但是其中一个字段应该是数字列表。我怎样才能做到这一点 ?(JSON?)
回答 0
如果您的服务器期望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
https://stackoverflow.com/a/26876308/496445
如果不指定标题,它将是默认application/x-www-form-urlencoded
类型。
回答 1
我建议使用令人难以置信的requests
模块。
http://docs.python-requests.org/zh-CN/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)
回答 2
对于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)
回答 3
这非常适合 Python 3.5
,如果URL中包含查询字符串/参数值,
请求网址= https://bah2.com/ws/rest/v1/concept/
参数值= 21f6bb43-98a1-419d-8f0c-8133669e40ca
import requests
url = 'https://bahbah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), verify=False, json=data)
print(r.status_code)
回答 4
您必须添加标题,否则会出现http 400错误。该代码在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)
回答 5
这是一个如何使用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)
回答 6
在最新的请求包中,您可以使用json
in requests.post()
方法来发送json dict,并且Content-Type
in标头将设置为application/json
。无需显式指定标头。
import requests
payload = {'key': 'value'}
requests.post(url, json=payload)
回答 7
这对我使用api来说效果很好
import requests
data={'Id':id ,'name': name}
r = requests.post( url = 'https://apiurllink', data = data)