Python3:JSON POST请求没有请求库

时间:2014-08-25 17:49:07

标签: php python json urllib

我想仅使用本机Python库将JSON编码数据发送到服务器。我喜欢请求,但我根本无法使用它,因为我无法在运行脚本的机器上使用它。我不需要这样做。

newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"} 
params = urllib.parse.urlencode(newConditions)
params = params.encode('utf-8')

req = urllib.request.Request(conditionsSetURL, data=params)
urllib.request.urlopen(req)        

我的服务器是本地WAMP服务器。我总是得到一个

  

urllib.error.HTTPError:HTTP错误500:内部服务器错误

100%肯定这是 NOT 服务器问题,因为同一台机器上具有相同网址的相同数据与同一服务器有效请求库和邮递员。

1 个答案:

答案 0 :(得分:38)

您没有发布JSON,而是发布application/x-www-form-urlencoded请求。

编码为JSON并设置正确的标题:

import json

newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"} 
params = json.dumps(newConditions).encode('utf8')
req = urllib.request.Request(conditionsSetURL, data=params,
                             headers={'content-type': 'application/json'})
response = urllib.request.urlopen(req)

演示:

>>> import json
>>> import urllib.request
>>> conditionsSetURL = 'http://httpbin.org/post'
>>> newConditions = {"con1":40, "con2":20, "con3":99, "con4":40, "password":"1234"} 
>>> params = json.dumps(newConditions).encode('utf8')
>>> req = urllib.request.Request(conditionsSetURL, data=params,
...                              headers={'content-type': 'application/json'})
>>> response = urllib.request.urlopen(req)
>>> print(response.read().decode('utf8'))
{
  "args": {}, 
  "data": "{\"con4\": 40, \"con2\": 20, \"con1\": 40, \"password\": \"1234\", \"con3\": 99}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Connection": "close", 
    "Content-Length": "68", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "Python-urllib/3.4", 
    "X-Request-Id": "411fbb7c-1aa0-457e-95f9-1af15b77c2d8"
  }, 
  "json": {
    "con1": 40, 
    "con2": 20, 
    "con3": 99, 
    "con4": 40, 
    "password": "1234"
  }, 
  "origin": "84.92.98.170", 
  "url": "http://httpbin.org/post"
}