Python3:不带请求库的JSON POST请求 [英] Python3: JSON POST Request WITHOUT requests library
问题描述
我想仅使用本机Python库将JSON编码的数据发送到服务器.我喜欢请求,但是我不能使用它,因为我不能在运行脚本的计算机上使用它.我需要没有它.
I want to send JSON encoded data to a server using only native Python libraries. I love requests but I simply can't use it because I can't use it on the machine which runs the script. I need to do it without.
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服务器.我总是得到一个
My server is a local WAMP server. I always get an
urllib.error.HTTPError:HTTP错误500:内部服务器错误
urllib.error.HTTPError: HTTP Error 500: Internal Server Error
我 100%确定,这不是不是服务器问题,因为在同一台计算机上,同一台服务器上使用相同的数据,使用相同的网址与请求库和邮递员.
I am 100% sure that this is NOT a server issue, because the same data, with the same url, on the same machine, with the same server works with the requests library and Postman.
推荐答案
您未发布JSON,而是正在发布application/x-www-form-urlencoded
请求.
You are not posting JSON, you are posting a application/x-www-form-urlencoded
request.
编码为JSON并设置正确的标头:
Encode to JSON and set the right headers:
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"
}
这篇关于Python3:不带请求库的JSON POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!