Python3:JSON POST请求没有请求库

mor*_*tzg 26 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)        
Run Code Online (Sandbox Code Playgroud)

我的服务器是本地Wamp服务器.我总是得到一个

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

100%确定不是服务器问题,因为同一台机器上具有相同网址的相同数据与同一服务器一起使用请求库.(也适用于发送POST请求的程序).我无法找出它为什么这样做......我自己编写了API.

Mar*_*ers 46

您没有发布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)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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"
}
Run Code Online (Sandbox Code Playgroud)

  • @Startec:通过使用`data`参数,`Request`对象从GET切换到POST. (3认同)
  • @Startec:不,`json.dumps()`生成一个*JSON编码的字符串*,其中整数仍然是(JSON)整数.任何兼容的JSON解码器都会再次为您提供整数. (3认同)
  • 请求的类型(即“post”)在哪里标识? (2认同)
  • @Startec:你不能。请参阅[如何使用 urllib2 创建 HTTP DELETE 方法?](http://stackoverflow.com/q/4511598) 了解解决方法。 (2认同)
  • @Startec:`newConditions`是一个*Python字典*,而不是一个JSON字符串. (2认同)