python requests post怎么用

备案号:蜀ICP备2026035467号-3|网址:www.xservx.com

一、python requests post怎么用|核心原理与基础认知

Python 的 requests 库是目前最流行的 HTTP 库之一,专为简化 HTTP 请求而设计,其 API 设计简洁、符合直觉,极大降低了网络请求开发门槛。其中 requests.post() 方法用于向指定 URL 发送 POST 类型的 HTTP 请求,常用于提交表单数据、上传文件、调用 API 接口等场景。作为 HTTP/1.1 协议中定义的请求方法,POST 用于向服务器提交数据,与 GET 方法(仅用于获取数据)有本质区别:POST 请求的数据通常包含在请求体中,而非 URL 查询参数中,因此更适合传输大量或敏感数据。

从请求结构来看,一次标准的 POST 请求包含以下核心组成部分:

在 Python 中,使用 requests.post() 的基本语法为:

response = requests.post(url, data=None, json=None, **kwargs)

其中:url 为目标地址,data 用于发送表单数据(application/x-www-form-urlencoded),json 用于发送 JSON 数据(application/json),**kwargs 支持传入 headers、cookies、timeout、proxies、verify 等参数。

需要特别注意的是:当同时指定 data 和 json 参数时,json 会覆盖 data,且自动设置 Content-Type: application/json。若仅使用 data,默认 Content-Type 为 application/x-www-form-urlencoded;若要发送 JSON 字符串,需手动设置请求头。

与其他语言(如 JavaScript 的 fetch 或 Java 的 HttpURLConnection)相比,requests 的优势在于其高度封装、自动处理重定向、会话保持、连接池复用等机制,开发者可专注于业务逻辑,而非底层细节。

【核心特性速览】

  • ✓ 支持表单、JSON、文件、流式等多种数据格式提交
  • ✓ 自动处理 URL 编码、Content-Type 识别
  • ✓ 内置会话(Session)支持,自动管理 cookies
  • ✓ 支持超时控制、重试策略、代理、SSL 验证
  • ✓ 响应对象提供状态码、头、文本、二进制、JSON 解析等便捷属性

💡 提示:requests 是第三方库,需先通过 pip install requests 安装。建议使用 Python 3.7+ 版本,以获得最佳兼容性与性能。

二、python requests post怎么用|基础用法与参数详解

掌握 requests.post() 的基础用法是进阶开发的前提。其完整函数签名如下:

requests.post(url, data=None, json=None, headers=None, cookies=None, files=None,
              auth=None, timeout=None, allow_redirects=True, proxies=None,
              verify=True, stream=None, cert=None)

下面逐项解析核心参数的实际含义与使用场景:

1. url:请求地址(必填)

可以是字符串(如 "https://httpbin.org/post")或 urllib.parse.urlparse 对象。注意:若 URL 包含中文或特殊字符,requests 会自动进行 URL 编码,无需手动处理。

2. data:表单数据(dict / list / bytes)

用于发送 application/x-www-form-urlencoded 格式数据,等效于 HTML 表单提交:

import requests
payload = {'username': 'testuser', 'password': '123456'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.json()['form'])
# 输出: {"username": "testuser", "password": "123456"}

3. json:JSON 数据(dict / list)

自动将数据序列化为 JSON 字符串,并设置 Content-Type: application/json 请求头:

payload = {'name': 'Alice', 'age': 28}
response = requests.post('https://httpbin.org/post', json=payload)
print(response.json()['json'])
# 输出: {"name": "Alice", "age": 28}

⚠️ 注意:若手动拼接 JSON 字符串(如 data='{"a":1}'),必须显式设置 headers={'Content-Type': 'application/json'},否则服务器可能无法正确解析!

4. headers:自定义请求头(dict)

用于模拟浏览器、传递认证信息等。例如添加 User-Agent 和 Accept-Language:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
    'Accept-Language': 'zh-CN,zh;q=0.9'
}
response = requests.post('https://httpbin.org/post', json={'data': 'test'}, headers=headers)

5. timeout:超时控制(float / tuple)

防止请求长时间挂起。支持两种形式:

推荐使用元组形式,实现更精细的控制:

try:
    response = requests.post('https://httpbin.org/delay/10', json={'a':1}, timeout=(3,6))
except requests.exceptions.Timeout:
    print('请求超时!')

6. allow_redirects:是否允许重定向(bool)

默认为 True。若需获取重定向后的最终 URL 或防止 302 跳转攻击,可设为 False:

response = requests.post('https://httpbin.org/redirect-to?url=https://example.com', allow_redirects=False)
print(response.status_code)  # 302
print(response.headers['Location'])  # https://example.com

7. 响应对象常用属性

属性说明示例
status_codeHTTP 状态码200, 404, 500
headers响应头(dict-like)response.headers['Content-Type']
text响应体(字符串)response.text
content响应体(二进制)response.content
json()解析 JSON 响应response.json()
url最终请求 URL(含重定向)response.url
elapsed请求耗时(timedelta)response.elapsed.total_seconds()

✅ 实用技巧:使用 response.raise_for_status() 可在状态码为 4xx/5xx 时主动抛出异常,便于统一异常处理。

三、python requests post怎么用|请求头(Headers)设置技巧

在实际开发中,请求头 是影响请求能否成功的关键因素之一。许多 API 要求特定的 Authorization、Content-Type 或 User-Agent 头,否则返回 401 或 400 错误。

1. 设置标准请求头

模拟真实浏览器行为,避免被反爬机制拦截:

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Content-Type': 'application/json',
    'Origin': 'https://example.com',
    'Referer': 'https://example.com/form'
}
response = requests.post('https://api.example.com/data', json={'key':'value'}, headers=headers)

2. 动态生成请求头

结合 datetime 和随机数生成唯一标识,增强请求真实性:

import random
from datetime import datetime
headers = {
    'X-Request-ID': f'req-{datetime.now().strftime("%Y%m%d%H%M%S")}-{random.randint(1000,9999)}',
    'X-Client-Version': '1.2.3',
    'X-Device-ID': 'device-abc123'
}

3. 处理特殊编码头

若需传递中文或特殊字符,requests 会自动进行 UTF-8 编码,但需确保服务端支持。例如:

headers = {'X-Custom-Header': '中文测试'}
# 实际发送时会被编码为: X-Custom-Header: %E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95

💡 提示:使用 response.request.headers 可查看请求实际发送的 headers,便于调试。

4. 常见请求头对照表

Header 名称作用示例值
Content-Type请求体数据格式application/json
AuthorizationBearer Token 认证Bearer eyJhbGciOiJIUzI1NiIs...
Cookie会话标识sessionid=abc123; csrftoken=xyz
X-CSRFTokenDjango 等框架防伪令牌xyz789
Accept-Encoding支持的压缩方式gzip, deflate, br

⚠️ 注意:某些网站(如 Google、Bing)会检查 User-Agent 是否为合法浏览器标识,若使用默认 Python-requests UA 可能被拒绝访问。建议使用真实浏览器 UA。

四、python requests post怎么用|表单数据(Form Data)提交详解

表单提交(application/x-www-form-urlencoded)是 Web 最常见的数据提交方式,尤其适用于传统 Web 应用和 API。requests 提供了便捷的 data 参数支持。

1. 基础表单提交

payload = {
    'username': 'admin',
    'password': 'secret123',
    'remember': 'true'
}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.json()['form'])
# 输出: {"username": "admin", "password": "secret123", "remember": "true"}

2. 多值参数(同名键)

当需要提交同名字段(如复选框)时,可使用列表或元组:

payload = [
    ('tag', 'python'),
    ('tag', 'requests'),
    ('tag', 'http')
]
response = requests.post('https://httpbin.org/post', data=payload)
print(response.json()['form'])
# 输出: {"tag": ["python", "requests", "http"]}

3. 文件上传(multipart/form-data)

虽然文件上传通常单独处理(见第五部分),但也可与表单数据混合提交:

files = {'file': open('report.pdf', 'rb')}
data = {'title': '月度报告', 'category': 'finance'}
response = requests.post('https://httpbin.org/post', data=data, files=files)
print(response.json()['files'])
# 输出: {"file": "PDF content..."}

4. 自定义 Content-Type 表单

某些 API 要求显式指定 Content-Type,即使使用 data:

headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post('https://api.example.com/login', data=payload, headers=headers)

✅ 实用技巧:使用 urllib.parse.urlencode() 可将字典手动编码为字符串,适用于需要精确控制编码格式的场景:

from urllib.parse import urlencode
encoded = urlencode(payload, doseq=True)  # 支持列表值
response = requests.post(url, data=encoded, headers={'Content-Type': 'application/x-www-form-urlencoded'})

5. 表单数据 vs JSON 数据对比

特性表单数据(data)JSON 数据(json)
默认 Content-Typeapplication/x-www-form-urlencodedapplication/json
数据格式key1=val1&key2=val2JSON 对象字符串
嵌套支持需手动编码(如 key[nested]=value)原生支持
二进制支持不支持(需用 files)不支持(需 Base64 编码)
适用场景传统 Web 表单、简单 APIRESTful API、现代 Web 服务

💡 提示:在现代 API 设计中,JSON 提交已成为主流,因其结构清晰、支持复杂嵌套、且与 JavaScript 原生兼容。但某些遗留系统仍要求表单格式,需根据服务端要求灵活选择。

五、python requests post怎么用|JSON 数据提交实战

JSON(JavaScript Object Notation)已成为 Web API 的标准数据交换格式,因其轻量、易读、语言无关的特性被广泛采用。requests 通过 json 参数提供了零配置的 JSON 提交能力。

1. 基础 JSON 提交

payload = {
    'user': {
        'id': 1001,
        'name': '张三',
        'tags': ['vip', 'active']
    },
    'action': 'update_profile'
}
response = requests.post('https://api.example.com/user/update', json=payload)

requests 会自动完成以下操作:

2. 嵌套对象与数组处理

requests 完美支持复杂嵌套结构,无需手动转换:

payload = {
    'order': {
        'id': 'ORD20241101',
        'items': [
            {'product': 'iPhone 15', 'qty': 1, 'price': 6999.00},
            {'product': 'AirPods Pro', 'qty': 2, 'price': 1899.00}
        ],
        'total': 10797.00,
        'metadata': {'source': 'mobile_app', 'campaign': 'double11'}
    }
}

3. 与表单提交混合使用

某些 API 要求 JSON 与表单字段混合提交(较少见),可通过 data + json 组合实现,但需注意:json 会覆盖 data 的 Content-Type 设置:

# 错误做法:data 会被 json 覆盖
# requests.post(url, data={'a':1}, json={'b':2})
# 正确做法:仅使用 json,或手动构造 multipart
import json
payload = json.dumps({'b':2})
files = {'file': ('data.txt', '{"a":1}', 'application/json')}
response = requests.post(url, files=files, data={'meta': payload})

4. JSON 响应解析

使用 response.json() 可直接解析返回的 JSON 数据:

if response.status_code == 200:
    data = response.json()
    print(data['user']['name'])  # 张三
else:
    print(f'请求失败: {response.status_code}')

⚠️ 注意:若响应体不是合法 JSON(如 HTML 错误页),response.json() 会抛出 JSONDecodeError。建议先检查 Content-Type 或使用 try-except:

try:
    data = response.json()
except ValueError:
    print('响应不是有效 JSON!')

5. 自定义 JSON 编码器

对于日期、Decimal 等非标准类型,可自定义 encoder:

import json
from datetime import datetime
from decimal import Decimal
class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        if isinstance(obj, Decimal):
            return float(obj)
        return super().default(obj)
payload = {'time': datetime.now(), 'amount': Decimal('100.50')}
json_str = json.dumps(payload, cls=CustomEncoder)
response = requests.post(url, data=json_str, headers={'Content-Type': 'application/json'})

✅ 实用技巧:使用 json.dumps(payload, ensure_ascii=False) 可保留中文字符,避免转义为 \uXXXX 形式。

六、python requests post怎么用|文件上传(multipart/form-data)

文件上传是 POST 请求的重要应用场景,requests 通过 files 参数以 multipart/form-data 格式实现。该格式支持二进制数据传输,并可同时上传多个文件和表单字段。

1. 单文件上传

with open('avatar.jpg', 'rb') as f:
    files = {'file': f}
    response = requests.post('https://httpbin.org/post', files=files)

2. 指定文件名与 Content-Type

默认文件名为文件路径,可通过元组指定自定义名称和 MIME 类型:

files = {
    'avatar': ('profile.jpg', open('avatar.jpg', 'rb'), 'image/jpeg')
}
response = requests.post('https://api.example.com/upload', files=files)

3. 多文件上传

一次请求提交多个文件:

files = [
    ('images', ('a.jpg', open('a.jpg', 'rb'), 'image/jpeg')),
    ('images', ('b.png', open('b.png', 'rb'), 'image/png'))
]
response = requests.post('https://httpbin.org/post', files=files)

4. 文件与表单字段混合提交

files = {'file': open('report.pdf', 'rb')}
data = {'title': '年度报告', 'year': '2024'}
response = requests.post('https://httpbin.org/post', data=data, files=files)

5. 内存中文件( StringIO / BytesIO)

无需真实文件,直接上传内存数据:

from io import BytesIO
content = b'Hello, World!'
files = {'data': ('message.txt', BytesIO(content), 'text/plain')}
response = requests.post('https://httpbin.org/post', files=files)

💡 提示:使用 with open(...) 上下文管理器可确保文件自动关闭,避免资源泄漏。

6. 大文件分块上传(流式)

对超大文件,建议启用流式上传以节省内存:

with open('large_file.zip', 'rb') as f:
    files = {'file': ('archive.zip', f, 'application/zip')}
    response = requests.post('https://upload.example.com', files=files, stream=True)

⚠️ 注意:某些服务器(如 Nginx)对上传文件大小有限制(默认 1MB)。若需上传大文件,需同时调整服务端配置(如 nginx 的 client_max_body_size)。

7. 文件上传进度监控

结合 requests_toolbelt 库可实现上传进度回调:

from requests_toolbelt import MultipartEncoder
import requests
def progress_callback(monitor):
    print(f'\r上传进度: {monitor.bytes_read / monitor.len * 100:.2f}%', end='')
m = MultipartEncoder(fields={
    'file': ('data.txt', open('data.txt', 'rb'), 'text/plain'),
    'desc': '测试文件'
})
monitor = requests.adapters.HTTPAdapter().build_response(m, progress_callback).request
response = requests.post('https://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})

七、python requests post怎么用|超时与重试机制

网络请求存在不确定性,设置合理的超时时间是生产级应用的必备措施。requests 提供了灵活的超时控制,并支持自定义重试策略。

1. 基础超时设置

try:
    response = requests.post('https://httpbin.org/delay/5', json={'a':1}, timeout=3)
except requests.exceptions.Timeout:
    print('请求超时!建议重试或调整超时值')

2. 分阶段超时(连接 vs 读取)

连接超时(connect timeout):建立 TCP 连接的时间
读取超时(read timeout):等待服务器响应的时间

response = requests.post('https://httpbin.org/delay/10', timeout=(3, 7))

3. 全局超时配置(Session)

通过 Session 设置默认超时,避免重复传参:

session = requests.Session()
session.timeout = 5  # 全局默认超时
response = session.post('https://httpbin.org/post', json={'data':'test'})

💡 提示:Session 的 timeout 属性需通过自定义适配器实现,见下一节重试机制。

4. 自定义重试策略

使用 urllib3.util.retry.Retry 实现自动重试:

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry_strategy = Retry(
    total=3,  # 总重试次数
    backoff_factor=1,  # 重试间隔:1s, 2s, 4s...
    status_forcelist=[500, 502, 503, 504],
    allowed_methods=["POST"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount("https://", adapter)
session.mount("http://", adapter)
try:
    response = session.post('https://httpbin.org/status/500', json={'a':1})
except Exception as e:
    print(f'重试失败: {e}')  # 输出: 重试失败: 500 Server Error...

5. 指数退避重试(Exponential Backoff)

避免短时间高频重试导致服务雪崩:

import time
import random
def post_with_backoff(url, data, max_retries=5):
    for i in range(max_retries):
        try:
            return requests.post(url, json=data, timeout=(3,7))
        except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
            if i == max_retries - 1:
                raise e
            wait_time = 2**i + random.uniform(0, 1)
            time.sleep(wait_time)
response = post_with_backoff('https://api.example.com/data', {'key':'value'})

✅ 实用技巧:生产环境建议结合 try-except + logging 记录失败请求,便于后期分析与告警。

八、python requests post怎么用|异常处理与调试技巧

网络请求中常见的异常类型多样,完善的异常处理是保障程序健壮性的关键。requests 定义了清晰的异常继承体系。

1. requests 异常继承树

Exception
└── RequestException
    ├── HTTPError
    ├── ConnectionError
    ├── Timeout
    ├── URLRequired
    ├── TooManyRedirects
    ├── ConnectTimeout
    └── ReadTimeout

2. 常见异常捕获示例

import requests
try:
    response = requests.post('https://httpbin.org/delay/10', json={'a':1}, timeout=(2,3))
    response.raise_for_status()  # 主动触发 HTTPError
except requests.exceptions.Timeout:
    print('请求超时!建议检查网络或增加 timeout 值')
except requests.exceptions.ConnectionError:
    print('连接失败!请检查目标服务器是否可达')
except requests.exceptions.HTTPError as e:
    print(f'HTTP 错误: {e.response.status_code}')
except requests.exceptions.RequestException as e:
    print(f'未知请求错误: {e}')

3. 详细异常信息获取

通过 response 对象获取更多调试信息:

try:
    response = requests.post(url, json=data, timeout=5)
except requests.exceptions.RequestException as e:
    print(f'请求失败: {e}')
    if hasattr(e, 'response') and e.response:
        print(f'响应状态: {e.response.status_code}')
        print(f'响应内容: {e.response.text[:200]}')  # 截断输出

4. 日志记录与告警

结合 logging 模块记录异常上下文:

import logging
logging.basicConfig(level=logging.INFO)
try:
    response = requests.post(url, json=data)
except Exception as e:
    logging.error(f'POST {url} 失败: {e}', exc_info=True)

5. 调试请求详情

使用 requests_toolbelt 的 dump 工具打印完整请求/响应:

from requests_toolbelt.utils import dump
try:
    response = requests.post('https://httpbin.org/post', json={'test':1})
    data = dump.dump_all(response)
    print(data.decode('utf-8'))
except Exception as e:
    print(f'调试失败: {e}')

💡 提示:生产环境建议关闭详细日志,避免敏感数据(如密码)泄露。

6. 自定义异常处理器

封装通用异常处理函数:

def safe_post(url, **kwargs):
    try:
        return requests.post(url, **kwargs)
    except requests.exceptions.Timeout:
        raise TimeoutError(f'请求 {url} 超时')
    except requests.exceptions.ConnectionError:
        raise ConnectionError(f'无法连接到 {url}')
    except requests.exceptions.HTTPError as e:
        raise RuntimeError(f'HTTP {e.response.status_code}: {e.response.text[:100]}')
try:
    response = safe_post('https://httpbin.org/status/404')
except RuntimeError as e:
    print(e)  # 输出: HTTP 404: ...

九、python requests post怎么用|会话保持与 Cookie 管理

在需要登录状态的网站中,会话保持(Session)是关键。requests 的 Session 对象可自动管理 cookies,实现跨请求状态延续。

1. 基础会话使用

session = requests.Session()
session.get('https://httpbin.org/cookies/set?name=value')
response = session.get('https://httpbin.org/cookies')
print(response.json())  # {'cookies': {'name': 'value'}}

2. 登录场景模拟

模拟用户登录流程(先 GET 获取 CSRF Token,再 POST 提交凭证):

session = requests.Session()
# 1. 获取登录页以获取 cookies
session.get('https://example.com/login')
# 2. 提交登录表单
payload = {'username': 'user', 'password': 'pass'}
session.post('https://example.com/login', data=payload)
# 3. 访问需要登录的页面
response = session.get('https://example.com/profile')
print(response.text)

3. 手动设置 Cookies

直接添加 cookies(注意:Session.cookies 是字典类对象):

session = requests.Session()
session.cookies.set('sessionid', 'abc123', domain='.example.com')
session.cookies.set('csrftoken', 'xyz789', domain='.example.com')
response = session.post('https://example.com/api', json={'data':'test'})

4. Cookie 持久化(保存/加载)

使用 MozillaCookieJar 保存 cookies 到文件:

import http.cookiejar
# 保存 cookies
session = requests.Session()
session.cookies = http.cookiejar.MozillaCookieJar('cookies.txt')
session.get('https://httpbin.org/cookies/set?test=value')
session.cookies.save(ignore_discard=True, ignore_expires=True)
# 加载 cookies
session2 = requests.Session()
session2.cookies.load('cookies.txt', ignore_discard=True, ignore_expires=True)
response = session2.get('https://httpbin.org/cookies')
print(response.json())  # {'cookies': {'test': 'value'}}

⚠️ 注意:某些网站使用 HttpOnly 标记的 cookies(如 sessionid),无法通过 JS 访问,但 requests 仍可正常发送。切勿尝试通过 document.cookie 获取这些值!

5. Cookie 域与路径设置

精确控制 cookies 的作用域:

session.cookies.set('token', 'abc', domain='api.example.com', path='/v1')

6. 会话参数继承

Session 可继承 headers、auth 等配置,减少重复代码:

session = requests.Session()
session.headers.update({'User-Agent': 'MyApp/1.0'})
session.auth = ('user', 'pass')  # 基础认证
# 以下请求自动携带 User-Agent 和 auth
session.post('https://api.example.com/data', json={'a':1})

✅ 实用技巧:使用 session.close() 显式关闭连接池,释放资源(尤其在脚本末尾)。

十、python requests post怎么用|代理服务器设置

代理服务器可隐藏真实 IP、突破访问限制或加速请求。requests 支持 HTTP/HTTPS/SOCKS 代理。

1. 单一代理设置

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080'
}
response = requests.post('https://api.example.com', json={'a':1}, proxies=proxies)

2. 代理认证

带用户名密码的代理:

proxies = {
    'http': 'http://user:pass@10.10.1.10:3128/',
    'https': 'http://user:pass@10.10.1.10:1080/'
}

3. 本地代理(如 Charles/Fiddler)

调试时常用本地代理监听请求:

proxies = {'http': 'http://localhost:8888', 'https': 'http://localhost:8888'}

4. 无代理绕过(直接连接)

跳过某些域名的代理:

proxies = {
    'http': None,
    'https': None,
    'no_proxy': 'localhost,127.0.0.1,example.com'
}

💡 提示:设置 no_proxy 时,建议包含常见本地地址(如 127.0.0.1、localhost),避免调试工具无法捕获本地请求。

5. 动态代理池(高级技巧)

结合代理池服务实现 IP 轮换:

import random
def get_random_proxy():
    proxies = [
        {'http': 'http://ip1:port', 'https': 'http://ip1:port'},
        {'http': 'http://ip2:port', 'https': 'http://ip2:port'}
    ]
    return random.choice(proxies)
response = requests.post(url, json=data, proxies=get_random_proxy())

6. 代理错误处理

try:
    response = requests.post(url, json=data, proxies=proxies)
except requests.exceptions.ProxyError:
    print('代理连接失败!检查代理配置或更换代理')
except requests.exceptions.SSLError:
    print('代理 SSL 握手失败!可能代理不支持 HTTPS')

⚠️ 注意:使用公共免费代理存在安全风险(可能记录请求内容)。生产环境建议使用可信代理服务或自建代理池。

十一、python requests post怎么用|SSL 证书验证

HTTPS 请求默认启用 SSL 证书验证,防止中间人攻击。requests 使用系统证书库,但支持自定义验证策略。

1. 默认证书验证

自动验证服务器证书是否由受信任 CA 签发:

response = requests.post('https://api.example.com', json={'a':1})  # 正常通过

2. 自签名证书处理

对自签名证书(如本地开发环境),可选择忽略验证:

response = requests.post('https://localhost:8443/api', json={'a':1}, verify=False)

⚠️ 警告:verify=False 会触发 InsecureRequestWarning,且存在安全风险!仅限测试环境使用。

3. 自定义证书路径

指定额外的 CA 证书(如企业内部 CA):

response = requests.post('https://internal.example.com', json={'a':1}, verify='/path/to/ca-bundle.crt')

4. 客户端证书认证(双向 SSL)

服务器要求客户端提供证书(如 API 网关):

response = requests.post('https://secure.example.com',
                         json={'a':1},
                         cert=('/path/client.crt', '/path/client.key'))

5. 证书验证失败处理

try:
    response = requests.post(url, json=data, verify=True)
except requests.exceptions.SSLError as e:
    print(f'SSL 验证失败: {e}')
    # 建议:检查日期、域名、或使用自定义 CA

💡 提示:使用 certifi 库可获取最新 CA 证书列表(requests 默认依赖它):

import certifi
response = requests.post(url, json=data, verify=certifi.where())

6. 证书链验证

验证服务器证书链完整性(避免中间证书缺失):

response = requests.post('https://example.com', json={'a':1}, verify=True)
# requests 会自动验证完整证书链

十二、python requests post怎么用|重定向控制

POST 请求后服务器返回 301/302 时,requests 默认跟随重定向,但可能改变请求方法(POST→GET)。需根据场景控制重定向行为。

1. 默认重定向行为

POST 后 302 重定向时,requests 会自动将后续请求改为 GET(符合 RFC 标准):

response = requests.post('https://httpbin.org/redirect-to?url=https://example.com', data={'a':1})
print(response.status_code)  # 200(最终响应)
print(response.history)      # []  # 重定向历史

2. 禁用重定向

获取重定向地址,避免意外跳转:

response = requests.post('https://httpbin.org/redirect-to?url=https://example.com',
                         data={'a':1}, allow_redirects=False)
print(response.status_code)  # 302
print(response.headers['Location'])  # https://example.com

3. 限制重定向次数

防止无限重定向循环:

try:
    response = requests.post(url, data={'a':1}, max_redirects=3)
except requests.exceptions.TooManyRedirects:
    print('重定向次数过多!

💡 提示:某些网站(如 Google)对 POST 重定向有特殊处理,可能导致数据丢失。建议 POST 后使用 303 See Other(强制转 GET),或 307/308(保留原方法)。

4. 自定义重定向逻辑

拦截重定向并手动处理:

class CustomAdapter(HTTPAdapter):
    def send(self, request, **kwargs):
        response = super().send(request, **kwargs)
        if response.is_redirect and request.method == 'POST':
            # 自定义 POST 重定向逻辑(如保留数据)
            new_url = response.headers['Location']
            response = requests.post(new_url, data=request.body, headers=request.headers)
        return response
session = requests.Session()
session.mount('https://', CustomAdapter())

5. 重定向状态码对照表

状态码行为POST 重定向后方法
301永久重定向→ GET(大部分客户端)
302临时重定向→ GET(大部分客户端)
303其他(强制 GET)→ GET
307临时重定向(保留方法)→ POST
308永久重定向(保留方法)→ POST

十三、python requests post怎么用|流式响应与大文件下载

流式响应(streaming)可避免一次性加载大响应体到内存,适用于下载大文件或处理实时数据。

1. 启用流式响应

with requests.post('https://httpbin.org/stream/100', json={'a':1}, stream=True) as r:
    for line in r.iter_lines():
        if line:
            print(line.decode('utf-8'))

2. 分块下载大文件

with requests.post('https://example.com/download', json={'file_id':123}, stream=True) as r:
    r.raise_for_status()
    with open('large_file.zip', 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192):
            if chunk:  # 过滤 keep-alive chunks
                f.write(chunk)

3. 流式上传(大文件)

结合 iter_content 实现边读边发:

def file_generator(filepath, chunk_size=8192):
    with open(filepath, 'rb') as f:
        while True:
            data = f.read(chunk_size)
            if not data:
                break
            yield data
files = {'file': ('data.bin', file_generator('data.bin'), 'application/octet-stream')}
response = requests.post('https://httpbin.org/post', files=files)

💡 提示:使用 with 上下文管理器可确保响应自动关闭,释放底层连接。

4. 流式处理 JSON 数据

对流式 JSON(如 SSE),使用 iter_lines + json.loads:

with requests.post('https://example.com/stream', json={'query':'data'}, stream=True) as r:
    for line in r.iter_lines():
        if line:
            try:
                data = json.loads(line)
                print(f'收到数据: {data}')
            except json.JSONDecodeError:
                pass

5. 流式响应性能对比

模式内存占用适用场景
非流式(默认)高(整个响应体加载)小文件、API 响应
流式(stream=True)低(分块处理)大文件、实时数据

⚠️ 注意:启用 stream=True 后,必须手动消费响应体(如 iter_content 或 close()),否则连接无法复用!

十四、python requests post怎么用|认证方式详解

认证是 API 安全的核心。requests 内置多种认证机制,支持常见协议。

1. 基础认证(Basic Auth)

from requests.auth import HTTPBasicAuth
response = requests.post('https://httpbin.org/post',
                         json={'a':1},
                         auth=HTTPBasicAuth('user', 'pass'))

2. 摘要认证(Digest Auth)

from requests.auth import HTTPDigestAuth
response = requests.post('https://httpbin.org/digest-auth/auth/user/pass',
                         json={'a':1},
                         auth=HTTPDigestAuth('user', 'pass'))

3. Bearer Token 认证

常见于 OAuth2 和 JWT:

headers = {'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'}
response = requests.post('https://api.example.com/data', json={'a':1}, headers=headers)

4. OAuth1 认证

使用 requests_oauthlib 库:

from requests_oauthlib import OAuth1
import requests
oauth = OAuth1('client_key', client_secret='client_secret',
               resource_owner_key='resource_key',
               resource_owner_secret='resource_secret')
response = requests.post('https://api.twitter.com/1.1/statuses/update.json',
                         data={'status':'Hello!'}, auth=oauth)

5. 自定义认证类

实现特殊认证逻辑(如 AWS Signature):

from requests.auth import AuthBase
import hmac
import hashlib
class HmacAuth(AuthBase):
    def __init__(self, key, secret):
        self.key = key
        self.secret = secret
    def __call__(self, r):
        message = (r.method + r.path_url).encode('utf-8')
        signature = hmac.new(self.secret.encode(), message, hashlib.sha256).hexdigest()
        r.headers['X-Signature'] = signature
        r.headers['X-Key'] = self.key
        return r
response = requests.post('https://api.example.com/data',
                         json={'a':1},
                         auth=HmacAuth('mykey', 'mysecret'))

💡 提示:使用 Session 可统一设置认证信息,避免重复传参:

session = requests.Session()
session.auth = ('user', 'pass')

6. 会话认证 vs 请求认证

方式适用场景优点
请求级(auth=)单次请求灵活控制
会话级(session.auth)多请求复用代码简洁

十五、python requests post怎么用|综合实战案例

以下是一个完整的生产级 POST 请求示例,整合了上述所有最佳实践:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import logging
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 1. 创建带重试的 Session
session = requests.Session()
retry_strategy = Retry(
    total=3,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["POST"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
session.mount("http://", adapter)
# 2. 设置通用配置
session.headers.update({
    'User-Agent': 'MyApp/1.0 (Windows NT 10.0; Win64; x64)',
    'Accept': 'application/json',
    'Content-Type': 'application/json'
})
session.auth = ('api_user', 'api_pass')  # 基础认证
session.proxies = {'https': 'http://proxy.example.com:8080'}  # 代理(可选)
# 3. 定义安全 POST 函数
def safe_post(url, data, timeout=(5, 10)):
    try:
        response = session.post(url, json=data, timeout=timeout)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.Timeout:
        logger.error(f'请求 {url} 超时')
        raise
    except requests.exceptions.HTTPError as e:
        logger.error(f'HTTP 错误: {e.response.status_code} - {e.response.text[:200]}')
        raise
    except Exception as e:
        logger.error(f'未知错误: {e}')
        raise
# 4. 执行业务逻辑
try:
    payload = {
        'user_id': 1001,
        'action': 'update_profile',
        'profile': {
            'name': '张三',
            'email': 'zhangsan@example.com',
            'tags': ['vip', 'active']
        }
    }
    result = safe_post('https://api.example.com/v2/user/update', payload)
    logger.info(f'更新成功: {result.get("message")}')
    # 5. 文件上传补充
    with open('avatar.jpg', 'rb') as f:
        files = {'avatar': ('avatar.jpg', f, 'image/jpeg')}
        upload_result = session.post('https://api.example.com/upload', files=files)
        logger.info(f'头像上传: {upload_result.status_code}')
except Exception as e:
    logger.error(f'流程失败: {e}')
finally:
    session.close()  # 释放资源

✅ 实用技巧:将上述配置封装为模块,可复用于项目所有 POST 请求,提升开发效率。

案例亮点总结

十六、网友还关心:python requests post 常见问题汇总

以下是网民在学习 python requests post 怎么用 过程中高频提问的问题及专业解答:

Q1: requests.post() 和 requests.request('POST', ...) 有什么区别?

A:两者功能等价,但 requests.post() 是语法糖,内部调用 requests.request('POST', ...)。推荐直接使用前者,更简洁直观。

Q2: 为什么 POST 请求后服务器没收到数据?

A:常见原因包括:

Q3: 如何在 POST 请求中传递数组参数?

A:根据服务端要求选择格式:

Q4: requests.post() 支持 HTTPS 吗?

A:完全支持!HTTPS 是默认启用的。若遇证书问题,可临时用 verify=False(仅测试环境),或配置自定义 CA 证书。

Q5: 如何设置 POST 请求的 Content-Length?

A:requests 会自动计算并设置 Content-Length,无需手动指定。手动设置可能导致头冲突,引发服务器拒绝请求。

Q6: POST 请求返回 400 错误,如何排查?

A:按以下步骤检查:

  1. 查看响应内容(response.text)获取详细错误信息
  2. 检查请求头(response.request.headers)是否符合要求
  3. 验证数据格式(JSON 表单是否有效)
  4. 使用 curl/Postman 复现请求,对比差异

Q7: requests.post() 能用于 WebSocket 吗?

A:不能!WebSocket 是独立协议(ws:// 或 wss://),需使用 websockets 或 socket.io-client 库。POST 是 HTTP 方法,不适用于长连接。

Q8: 如何实现 POST 请求的异步并发?

A:建议使用 aiohttp(原生异步)或 concurrent.futures.ThreadPoolExecutor + requests:

from concurrent.futures import ThreadPoolExecutor
def post_task(data):
    return requests.post('https://httpbin.org/post', json=data).json()
with ThreadPoolExecutor(max_workers=5) as executor:
    results = list(executor.map(post_task, [{'a':i} for i in range(10)]))

Q9: requests.post() 有大小限制吗?

A:理论上无硬限制,但受以下因素影响:

大文件建议分块上传或使用流式处理。

Q10: 如何测试 POST 请求是否成功?

A:综合判断指标:

💡 提示:使用 pytest + requests 可编写自动化测试,确保接口稳定性。

网友关注的周边话题

⚠️ 安全提醒:生产环境中请勿硬编码密码、API Key 等敏感信息!建议使用环境变量或配置中心管理。