【问题标题】:Python send JSON using HTTP POSTPython 使用 HTTP POST 发送 JSON
【发布时间】:2015-02-13 11:35:47
【问题描述】:

我需要使用 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

【问题讨论】:

标签: python json curl http-post


【解决方案1】:

您没有将标头传递给 Request 您至少需要指定内容类型(就像您调用 curl 时所做的那样)

应该是这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多