Python3:没有请求库的JSON POST请求

2024-04-23 21:14:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想只使用本地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 Error 500: Internal Server Error

我100%确信这不是服务器问题,因为相同的数据、相同的url、相同的机器、相同的服务器与请求库和邮递员一起工作。


Tags: 数据服务器脚本机器json编码request情况
1条回答
网友
1楼 · 发布于 2024-04-23 21:14:02

您没有发布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"
}

相关问题 更多 >