如何在Python中发送含自定义非JSON文本的POST请求
使用Python requests发送纯文本POST请求
要实现发送纯文本格式的POST请求,只需按以下方式操作:
- 用
data参数传递纯文本内容(不要使用json参数,该参数会自动将内容序列化为JSON并设置对应请求头) - 手动设置请求头的
Content-Type为text/plain
完整代码示例
import requests url = "https://www.example.re" text_content = "I really like cheese, but I hate it in JSON format!" headers = {"Content-Type": "text/plain"} response = requests.post(url, data=text_content, headers=headers) # 可通过以下方式验证请求结果 print(response.status_code) print(response.text)
常见问题说明
如果之前尝试失败,大概率是误用了json参数——使用该参数时,requests会自动将内容转为JSON字符串,同时把Content-Type设为application/json,不符合纯文本需求。而直接用data传递字符串时,requests默认的Content-Type是application/x-www-form-urlencoded,因此必须手动指定为text/plain才能匹配目标请求格式。
内容的提问来源于stack exchange,提问作者Tal Moshel
相关产品推荐
相关产品推荐

