繁体   English   中英

Python 请求不发送 {"Content-Type":"application/json"} 标头或只是忽略 HTTP POST 中的正文

[英]Python requests not sending {"Content-Type":"application/json"} header or is just ignoring body in HTTP POST

我正在编写一些 Python 来与使用 RESTful 的 API 进行通信。 我已经管理了许多成功的 GET 命令,但是在使用 POST 时遇到了困难。 HTTP POST 正在通过,我收到 200 OK 响应和数据,但我使用 POST 发送的正文没有被读取。

import requests
url = "http://example.co.uk/dir"
body = {"obj1":1, "obj2":2}
headers = {"Accept":"application/json"}
s = requests.Session()
req = requests.Request("POST", url, json=body, headers=headers)
prepped = req.prepare()
print(prepped.headers)
response = s.send(prepped)
print(response.request.headers)

print(prepped.headers)显示:

{"Accept": "application/json","Content-Length":"19","Content-Type":"application/json"}

但是, print(response.request.headers)的结果仅显示:

{"Accept": "application/json"}

我也尝试过使用以下方法:

request.post(url, json=body, headers=headers)

并且还尝试手动创建“Content-Type”并使用 data=body 和 json 模块:

headers = {"Accept":"application/json", "Content_Type":"application/json"}
body = json.dumps(body)
request.post(url, data=body, headers=headers)

每次我收到 200 OK 状态和一些格式正确的数据,但好像 API 忽略了正文。 任何帮助或指示将不胜感激。

在您的示例中,您使用的是 HTTP。 确保使用 HTTPS 请求,因为这可能是一个问题,具体取决于您正在处理的 API。

import requests
s = requests.session()
s.headers = headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}
https = s.post("https://reqbin.com/echo/post/json", json={"foo": "bar"})
print(https.status_code)
print(https.request.headers)

http = s.post("http://reqbin.com/echo/post/json", json={"foo": "bar"})
print(http.status_code)
print(http.request.headers)

结果是

200
{'Accept': 'application/json', 'Content-Type': 'application/json', 'Content-Length': '14'}
405
{'Accept': 'application/json'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM