requests.post()方法通过data、json和files参数分别处理表单、JSON和文件上传,结合headers可自定义请求头,实现灵活的POST请求。

Python的
requests
requests.post()
解决方案: 说实话,刚开始接触
requests
post()
最基础的POST请求,通常会带上一些数据。这些数据可以是表单形式(
application/x-www-form-urlencoded
application/json
对于表单数据,我们通常会用到
data
requests
import requests
url = "https://httpbin.org/post" # 这是一个测试POST请求的公共服务
payload = {
"name": "Alice",
"age": 30,
"city": "New York"
}
try:
response = requests.post(url, data=payload)
response.raise_for_status() # 如果状态码不是200,会抛出HTTPError异常
print("表单数据发送成功!")
print(response.json())
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")如果你需要发送JSON数据,
requests
json
Content-Type: application/json
json.dumps()
立即学习“Python免费学习笔记(深入)”;
import requests
url = "https://httpbin.org/post"
json_payload = {
"product_id": "P123",
"quantity": 5,
"options": ["color:red", "size:M"]
}
try:
response = requests.post(url, json=json_payload)
response.raise_for_status()
print("\nJSON数据发送成功!")
print(response.json())
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")有时,我们还需要自定义请求头,比如添加认证信息、User-Agent等,或者处理某些特定的
Content-Type
headers
import requests
url = "https://httpbin.org/post"
custom_headers = {
"User-Agent": "MyCustomApp/1.0",
"Authorization": "Bearer your_token_here",
"X-Custom-Header": "HelloFromPython"
}
payload = {"message": "This request has custom headers."}
try:
response = requests.post(url, data=payload, headers=custom_headers)
response.raise_for_status()
print("\n带自定义头的请求发送成功!")
print(response.json())
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")这是一个非常实际的问题,因为后端API对数据格式的要求五花八门。理解
requests
requests.post()
data
json
当你使用
data
requests
application/x-www-form-urlencoded
requests
Content-Type
import requests
url = "https://httpbin.org/post"
xml_data = "<root><item>Hello XML</item></root>"
headers = {"Content-Type": "application/xml"}
try:
response = requests.post(url, data=xml_data, headers=headers)
response.raise_for_status()
print("\n发送XML数据:")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")而
json
Content-Type
application/json
requests
json
json.dumps()
选择哪个参数,完全取决于你的API要求。如果API文档明确要求
application/x-www-form-urlencoded
data
application/json
json
requests.post()
文件上传是POST请求的另一个高频场景,比如上传图片、文档或者其他二进制文件。
requests
files
multipart/form-data
files
('filename', file_object)('filename', file_object, 'content_type', custom_headers)最常见的情况是上传单个文件:
import requests
import os
url = "https://httpbin.org/post"
# 假设我们有一个名为 'example.txt' 的文件
# 先创建一个模拟文件以供上传
file_path = "example.txt"
with open(file_path, "w") as f:
f.write("This is a test file content.\n")
f.write("Line two of the test file.")
try:
with open(file_path, "rb") as f: # 注意这里是'rb'模式,以二进制读取
files = {"upload_file": f} # 'upload_file'是服务器期望接收的文件字段名
response = requests.post(url, files=files)
response.raise_for_status()
print("\n文件上传成功!")
print(response.json())
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
finally:
if os.path.exists(file_path):
os.remove(file_path) # 清理模拟文件你甚至可以同时发送文件和其他表单数据,
requests
multipart/form-data
import requests
import os
url = "https://httpbin.org/post"
# 再次创建模拟文件
file_path_2 = "another_example.txt"
with open(file_path_2, "w") as f:
f.write("Another test file for combined upload.")
try:
with open(file_path_2, "rb") as f:
# 指定文件名和Content-Type,以及其他表单数据
files = {"document": ("report.txt", f, "text/plain")}
data = {"title": "Monthly Report", "year": 2023}
response = requests.post(url, files=files, data=data)
response.raise_for_status()
print("\n文件与表单数据一同上传成功!")
print(response.json())
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
finally:
if os.path.exists(file_path_2):
os.remove(file_path_2以上就是python requests库如何发送post请求_python requests库POST请求发送方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号