在Python中使用自定义非JSON内容发送post请求

6ju8rftf  于 2023-10-14  发布在  Python
关注(0)|答案(1)|浏览(104)

我试图创建一个特定URL的post请求,但我想传递的内容只是简单的文本,而不是JSON格式,例如:

POST / HTTP/1.1
Host: www.example.re
Content-Type: text/plain
Content-Length: 51
\r\n
I really like cheese, but I hate it in JSON format!

我试过使用python requests 模块,但它不允许我将内容定义为简单的文本。我在堆栈溢出上发现了一个类似的问题,但它仍然没有答案。
我真的很感激你的帮助。

h6my8fg2

h6my8fg21#

在标题中指定您的内容类型并使用data=。范例:

import requests

url = "https://httpbin.org/post"
text = "I really like cheese, but I hate it in JSON format!"

r = requests.post(url, headers={"Content-Type": "text/plain"}, data=text)
print(r.text)

回报率:

{
  "args": {}, 
  "data": "I really like cheese, but I hate it in JSON format!", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate, br", 
    "Content-Length": "51", 
    "Content-Type": "text/plain", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.31.0", 
    "X-Amzn-Trace-Id": "Root=1-65292575-75a3fa092e6553300077b82c"
  }, 
  "origin": "127.0.0.1", 
  "url": "https://httpbin.org/delay/1"
}

相关问题