Python使用HTTP POST发送JSON

时间:2015-02-13 11:35:48

标签: python json curl http-post

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

现在我使用curl并且它可以工作:

curl -X POST -H" Content-Type:application / json" -H"接受: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

1 个答案:

答案 0 :(得分:1)

您没有将标题传递给请求 您至少需要指定内容类型(正如您在调用 curl 时所做的那样)

会是这样的:

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