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

时间:2012-03-17 00:53:50

标签: python json http url post

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

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

8 个答案:

答案 0 :(得分:143)

如果您的服务器期望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 :(得分:101)

我建议使用令人难以置信的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)

答案 2 :(得分:49)

for 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 :(得分:13)

如果URL包含查询字符串/参数值

,则这适用于Python 3.5

请求网址= 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 :(得分: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 :(得分:1)

这是一个如何使用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 :(得分:1)

在最新请求包中,您可以在requests.post()方法中使用json参数发送json字典,并且标题中的Content-Type将设置为application/json。无需显式指定标头。

import requests

payload = {'key': 'value'}

requests.post(url, json=payload)

答案 7 :(得分:1)

这个对我来说适合使用api

<configuration>
<!-- some lines above ... -->
    <system.data>
        <DbProviderFactories>
            <add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" support="FF"/> 
        </DbProviderFactories>
    </system.data>
<!-- some lines below ... -->
</configuration>