首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将POST请求作为JSON发送?

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

Stack Overflow用户
提问于 2012-03-17 08:53:50
回答 8查看 331.6K关注 0票数 117
代码语言:javascript
复制
data = {
        'ids': [12, 3, 4, 5, 6 , ...]
    }
    urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data))

我想发送一个POST请求,但是其中一个字段应该是一个数字列表。我该怎么做呢?(JSON?)

EN

回答 8

Stack Overflow用户

发布于 2012-03-17 09:33:15

我推荐使用令人难以置信的requests模块。

http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers

代码语言:javascript
复制
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)
票数 119
EN

Stack Overflow用户

发布于 2014-11-12 07:07:42

对于python 3.4.2,我发现以下内容将会起作用:

代码语言:javascript
复制
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))
response = urllib.request.urlopen(req, jsondataasbytes)
票数 81
EN

Stack Overflow用户

发布于 2016-10-13 17:34:44

这对于Python 3.5非常有效,如果URL包含查询字符串/参数值,

请求URL = https://bah2.com/ws/rest/v1/concept/

参数值= 21f6bb43-98a1-419d-8f0c-8133669e40ca

代码语言:javascript
复制
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'), json=data)
print(r.status_code)
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9746303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档