如何用Python的requests库或其他工具发送非JSON格式POST请求?
使用Python发送非JSON格式的POST请求
requests包完全支持发送非JSON格式的POST请求,你之前的误解可能是因为常用了json=参数——其实它提供了多种方式指定不同格式的请求体:
1. 发送表单格式(application/x-www-form-urlencoded)
这是HTML表单默认的提交格式,直接用data=参数传递字典即可,requests会自动设置正确的Content-Type头:
import requests form_data = {'username': 'test_user', 'password': '123456'} response = requests.post('https://example.com/login', data=form_data)
2. 发送纯文本、XML等自定义文本格式
直接把字符串内容传给data=,然后手动设置对应的Content-Type请求头:
import requests # 纯文本示例 text_body = "这是一段纯文本请求体" headers = {'Content-Type': 'text/plain; charset=utf-8'} response = requests.post('https://example.com/text', data=text_body, headers=headers) # XML示例 xml_body = '''<user> <name>张三</name> <age>25</age> </user>''' headers = {'Content-Type': 'application/xml; charset=utf-8'} response = requests.post('https://example.com/xml', data=xml_body, headers=headers)
3. 发送二进制数据(如文件、字节流)
- 上传文件可以用
files=参数:
import requests with open('report.pdf', 'rb') as f: files = {'document': ('report.pdf', f, 'application/pdf')} response = requests.post('https://example.com/upload', files=files)
- 直接发送字节流的话,把bytes对象传给
data=,并设置Content-Type为application/octet-stream:
import requests binary_data = b'\x48\x65\x6c\x6c\x6f' # 对应"Hello"的字节 headers = {'Content-Type': 'application/octet-stream'} response = requests.post('https://example.com/binary', data=binary_data, headers=headers)
4. 备选工具(如果需要)
如果不想用requests,Python标准库的http.client或urllib.request也能实现,比如:
import http.client conn = http.client.HTTPSConnection("example.com") payload = "自定义文本内容" headers = {'Content-Type': 'text/plain'} conn.request("POST", "/post", payload, headers) response = conn.getresponse() print(response.read().decode('utf-8'))
总结:requests完全能覆盖非JSON请求体的需求,无需额外工具,核心是根据请求体格式选择合适的参数(data=/files=)并配置正确的请求头。
内容的提问来源于stack exchange,提问作者KosD
相关产品推荐
相关产品推荐

