[英]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.