Python 使用 HTTP POST 发送 JSON

Python send JSON using HTTP POST

我需要使用 POST 将简单的 JSON 发送到网络服务器。

现在我正在使用 curl 并且它有效:

curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"abc":123}' http://1.2.3.4:4321/api/test

如何在 python 中完成?

我写了:

import urllib2
import json
from json import JSONEncoder

jsonString= JSONEncoder().encode({ 
   "abc": 123
})
print 'JSON: ', jsonString

url = 'http://1.2.3.4:4321/api/test'
req = urllib2.Request(url, jsonString)
response = urllib2.urlopen(req)
print response.read()

但是它崩溃了:

/usr/bin/python2.7 /tmp/rest.py
JSON:  {"abc": 123}
Traceback (most recent call last):
  File "/tmp/rest.py", line 50, in <module>
    registerNewDevice()
  File "/tmp/rest.py", line 33, in registerNewDevice
    response = urllib2.urlopen(req)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 400: Bad Request

Process finished with exit code 1

您没有将 headers 传递给 Request 您至少需要指定 content-type(就像您调用 curl 时所做的那样)

会是这样的:

req = urllib2.Request(url, jsonString, {'Content-Type': 'application/json'})