在 Python 中,创建自定义 HTTP 客户端并拦截请求通常可以通过以下方式实现

2025-04-27ASPCMS社区 - fjmyhfvclm

在 Python 中,创建自定义 HTTP 客户端并拦截请求通常可以通过以下方式实现:

1. 使用 requests 库 + 自定义 Session

requests 是 Python 中最流行的 HTTP 客户端库,通过自定义 Session 对象,可以拦截请求和响应。

示例:拦截请求并修改 Headers

python

import requests

class CustomSession(requests.Session):

def request(self, method, url, **kwargs):

# 在发送请求前拦截并修改参数

print(f"Intercepted request to {url}")

kwargs.setdefault('headers', {}).update({'X-Custom-Header': 'Python-Interceptor'})

return super().request(method, url, **kwargs)

# 使用自定义 Session

session = CustomSession()

response = session.get('https://httpbin.org/get')

print(response.text) # 输出响应内容(包含自定义 Header)

2. 使用 urllib3 底层拦截

urllib3 是 requests 的底层库,提供了更底层的请求控制。

示例:自定义 HTTPAdapter

python

import urllib3

from requests.adapters import HTTPAdapter

aspcms.cn

class CustomAdapter(HTTPAdapter):

def send(self, request, **kwargs):

# 拦截请求并修改

print(f"Intercepted request to {request.url}")

request.headers['X-Custom-Header'] = 'Python-Interceptor'

return super().send(request, **kwargs)

# 使用自定义 Adapter

session = requests.Session()

session.mount('https://', CustomAdapter())

response = session.get('https://httpbin.org/get')

print(response.text)

3. 使用 mitmproxy(代理工具)

如果需要全局拦截请求(如调试或模拟网络环境),可以使用 mitmproxy 作为中间人代理。

示例:通过 mitmproxy 脚本拦截请求

安装 mitmproxy:

bash

pip install mitmproxy

编写拦截脚本 intercept.py:

python

from mitmproxy import http

def request(flow: http.HTTPFlow) -> None:

if "example.com" in flow.request.url:

flow.request.headers["X-Custom-Header"] = "mitmproxy-Interceptor"

flow.response = http.Response.make(200, b"Intercepted by mitmproxy", {"Content-Type": "text/plain"})

启动代理:

bash

mitmproxy -s intercept.py

配置客户端使用代理(如 http://localhost:8080)。

4. 使用 aiohttp(异步客户端)

对于异步 HTTP 请求,可以使用 aiohttp 并自定义 ClientSession。

示例:异步拦截请求

python

import aiohttp

import asyncio

async def custom_request(session, method, url, **kwargs):

全部评论