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)