登录
首页 >  文章 >  python教程

Pythonrequests发送POST请求教程

时间:2025-12-30 13:10:45 112浏览 收藏

对于一个文章开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《Python requests发送POST请求方法》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

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

python requests库如何发送post请求_python requests库POST请求发送方法

Python的requests库在发送POST请求时,提供了极其简洁且功能强大的接口,核心就是requests.post()方法。它能够轻松处理表单数据、JSON负载、文件上传乃至复杂的认证场景,让HTTP请求变得像呼吸一样自然,极大简化了开发者与Web服务交互的复杂性。

解决方案: 说实话,刚开始接触requests库的时候,我最喜欢的就是它发POST请求的简洁性。一个post()调用,几乎就能搞定大部分需求。但实际操作起来,远不止一个简单的调用那么直白,背后有很多细节值得我们琢磨,尤其是在处理不同数据类型和错误时。

最基础的POST请求,通常会带上一些数据。这些数据可以是表单形式(application/x-www-form-urlencoded),也可以是JSON格式(application/json)。

对于表单数据,我们通常会用到data参数,它接受一个字典,requests会自动将其编码为URL编码格式:

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参数。它会自动将你的Python字典序列化为JSON字符串,并设置正确的Content-Type: application/json头,省去了我们手动json.dumps()的麻烦。

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}")

如何发送不同类型的数据:表单、JSON与原始字节流?

这是一个非常实际的问题,因为后端API对数据格式的要求五花八门。理解requests如何处理这些差异,能省去不少调试的麻烦,尤其是当你的请求总是返回400 Bad Request的时候,多半是这里出了问题。

requests.post()方法在处理数据时,主要依赖datajson这两个参数。它们各自有明确的用途和隐式行为。

当你使用data参数时,requests默认会把你的字典或元组列表编码成application/x-www-form-urlencoded格式。这就像浏览器提交一个HTML表单时做的事情。如果你传入的是一个字符串或字节流,requests会直接将其作为请求体发送,此时你需要自己设置Content-Type头。比如,你想发送一段XML或者其他自定义格式的原始数据:

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参数,正如前面提到的,是为JSON数据量身定制的。它会自动帮你完成两件事:将Python字典或列表转换为JSON字符串,并且将Content-Type请求头设置为application/json。这是我个人觉得requests最方便的功能之一,因为它省去了手动导入json库再json.dumps()的步骤,让代码看起来更干净。

选择哪个参数,完全取决于你的API要求。如果API文档明确要求application/x-www-form-urlencoded,那就用data。如果要求application/jsonjson参数无疑是最佳选择。搞清楚这一点,能避免很多“为什么我的数据发不出去”的困惑。

使用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的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Pythonrequests发送POST请求教程》文章吧,也可关注golang学习网公众号了解相关技术文章。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>