You need to enable JavaScript to run this app. 如何使用Python requests发送用户自定义任意方法的HTTP请求
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python requests发送用户自定义任意方法的HTTP请求

自定义任意HTTP方法发送实现方案

最直接的无侵入实现

不需要修改requests源码,也不需要强制编写继承逻辑,直接调用requests.request()方法传入自定义的方法名参数即可。requests底层不会对HTTP方法名做严格白名单拦截,会直接将传入的字符串作为请求行的方法字段发送给目标:

import requests

# 替换为实际测试目标
target = "https://test-target.example/test-path"
# 任意自定义的非标准HTTP方法字符串
custom_method = "CUSTOM-TEST-ACTION"

resp = requests.request(
    method=custom_method,
    url=target,
    timeout=10,
    allow_redirects=False
)

print(f"状态码: {resp.status_code}")
print(f"响应内容片段: {resp.text[:500]}")

基于requests类继承的可复用封装

如果需要批量开展测试、复用会话配置(比如统一Cookie、代理、请求头),可以通过继承requests.Session(requests核心会话管理类)扩展自定义方法发送能力,完全兼容requests原有所有功能:

import requests

class CustomMethodSession(requests.Session):
    def send_custom_request(self, url: str, method_name: str, **kwargs):
        """发送任意自定义HTTP方法的请求,支持所有requests原生参数"""
        return self.request(method=method_name, url=url, **kwargs)

# 使用示例
if __name__ == "__main__":
    tester = CustomMethodSession()
    # 统一配置测试环境参数
    tester.headers.update({"User-Agent": "SecurityTest/1.0"})
    # 可搭配本地代理对接抓包工具调试
    tester.proxies = {"https": "http://127.0.0.1:8080"}

    # 批量测试多类非常规方法
    test_methods = ["FOO", "BAR", "INVALID-METHOD", "DEBUG-CUSTOM", "TRACE-INVALID"]
    for method in test_methods:
        try:
            resp = tester.send_custom_request(
                url="https://test-target.example/",
                method_name=method,
                timeout=10,
                allow_redirects=False
            )
            # 校验是否触发预期的错误页返回(通常为405/501状态码)
            print(f"方法: {method} | 状态码: {resp.status_code} | 触发错误页: {resp.status_code in (405, 501)}")
        except Exception as e:
            print(f"方法: {method} | 请求失败: {str(e)}")

测试场景注意事项

  • 自定义方法名仅需满足HTTP请求行的基础格式要求,不要携带空格、\r\n等特殊字符,避免引发请求格式异常或者触发WAF拦截。
  • 发送完成后建议通过抓包工具确认实际出网的请求方法为自定义值,排除中间网络节点(CDN、WAF)对非标准方法的拦截改写。
  • 安全测试场景下建议关闭自动重定向,避免目标站点对错误状态码做302跳转,导致无法拿到原生错误页的信息。
  • 无需被requests文档列出的标准HTTP方法列表限制,所有非空、无特殊字符的字符串都可以作为自定义方法名发送。

内容的提问来源于stack exchange,提问作者choonsik-star

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.08 07:54:03