简体   繁体   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

I'm writing some Python to communicate with an API, that uses RESTful.我正在编写一些 Python 来与使用 RESTful 的 API 进行通信。 I've managed many successful GET commands, however, am having difficulties with POST.我已经管理了许多成功的 GET 命令,但是在使用 POST 时遇到了困难。 The HTTP POST is going through and I'm getting a 200 OK response and data but the Body I'm sending with the POST isn't being read. 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)

Result of the print(prepped.headers) show: print(prepped.headers)显示:

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

However, results of the print(response.request.headers) only shows:但是, print(response.request.headers)的结果仅显示:

{"Accept": "application/json"}

I have also tried using the method:我也尝试过使用以下方法:

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

and also tried manually creating "Content-Type" and using data=body and the json module:并且还尝试手动创建“Content-Type”并使用 data=body 和 json 模块:

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

Every time I recieve the 200 OK Status and some data in the right format but as if the API has ignored the body.每次我收到 200 OK 状态和一些格式正确的数据,但好像 API 忽略了正文。 Any help or pointers would be greatly appreciated.任何帮助或指示将不胜感激。

In your example you're using HTTP.在您的示例中,您使用的是 HTTP。 Make sure to use HTTPS request as that can be an issue depending on the API you're dealing with.确保使用 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)

Results in结果是

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