跳转至

除浏览器外,发起 HTTP 请求的方式

约 337 个字 92 行代码 2 张图片 预计阅读时间 2 分钟

使用图形化界面

如:

  • Postman
    • 参数等的输入方式都是图形化的
    • 响应头能看的是参数,且要另看
    • 实体主题体根据类型不同会有格式化 Postman
  • ApiPost
  • ApiFox
  • Fiddler
    • 可以从原始的报文构建
    • 可以查看原始报文
  • Chromium 内核浏览器的开发人员工具的“网络控制台”

使用命令行界面

如:

  • curl
    • 常用于 Linux 中(Windows 的 PowerShell 里面的 curl 功能不一样)
    • 参数和可以实现的功能很多
  • httpie
    • 可使用 pip 安装
    • 默认情况下只显示响应报文
    • 添加 -v 选项可以同时看到 HTTP 请求和响应的报文
    • 官网文档:https://httpie.io/docs/cli
    使用示例

    http POST pie.dev/post hello=world -v
    
    输出
    POST /post HTTP/1.1
    Accept: application/json, */*;q=0.5
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
    Content-Length: 18
    Content-Type: application/json
    Host: pie.dev
    User-Agent: HTTPie/3.2.1
    
    {
        "hello": "world"
    }
    
    
    HTTP/1.1 200 OK
    Access-Control-Allow-Credentials: true
    Access-Control-Allow-Origin: *
    CF-Cache-Status: DYNAMIC
    CF-RAY: 71f11bee2df27c74-LAX
    Connection: keep-alive
    Content-Encoding: gzip
    Content-Type: application/json
    Date: Wed, 22 Jun 2022 01:11:17 GMT
    NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
    Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=Wlvo2%2B5PeLQWSSMgqJ5cL8MfG8yYtujgRxTJHs8QFNTSjcXzErjCNx6Gjk45jumt3KxkJMuTyrc%2FkC912NGxGLuUiSB86USObDGMFPk5Gaex4jeRidnNK946"}],"group":"cf-nel","max_age":604800}
    Server: cloudflare
    Transfer-Encoding: chunked
    
    Via: 1.1 ts.com (squid/3.5.20)
    X-Cache: MISS from ts.com
    X-Cache-Lookup: MISS from ts.com:3128
    alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
    
    {
        "args": {},
        "data": "{\"hello\": \"world\"}",
        "files": {},
        "form": {},
        "headers": {
            "Accept": "application/json, */*;q=0.5",
            "Accept-Encoding": "gzip",
            "Cache-Control": "max-age=259200",
            "Cdn-Loop": "cloudflare",
            "Cf-Connecting-Ip": "58.213.34.25",
            "Cf-Ipcountry": "CN",
            "Cf-Ray": "71f11bee2df27c74-FRA",
            "Cf-Visitor": "{\"scheme\":\"http\"}",
            "Connection": "Keep-Alive",
            "Content-Length": "18",
            "Content-Type": "application/json",
            "Host": "pie.dev",
            "User-Agent": "HTTPie/3.2.1"
        },
        "json": {
            "hello": "world"
        },
        "origin": "10.94.5.157,58.213.34.25",
        "url": "http://pie.dev/post"
    }
    
  • HTTPX
  • httpstat
    • 可使用 pip 安装
    • 用法和 curl 类似
    • 可显示时延
    • 请求、响应实体主题会被存到临时文件
    • 在有代理的情况下运行,需要先配置好系统代理的环境变量
      • 环境变量 HTTP_PROXY HTTPS_PROXY
      • 值的格式为:http://[用户名[:密码]@]代理地址:端口号/ httpstat

在编写程序时构建 HTTP 请求

对于 Python,最基本的是使用标准库 urllib 构建,但比较复杂:

from urllib import request, parse

data = parse.urlencode([
    ('param1', 1),
    ('param2', 'hello'),
    ('param3', '测试')
])

req = request.Request('http://httpbin.org/post')
req.add_header('User-Agent', 'ding_urllib_test')

with request.urlopen(req, data=data.encode('utf-8')) as f:
    print('Status:', f.status, f.reason)
    for k, v in f.getheaders():
        print('%s: %s' % (k, v))
    print('Data:', f.read().decode('utf-8'))
输出
Status: 200 OK
Date: Wed, 22 Jun 2022 08:36:12 GMT
Content-Type: application/json
Content-Length: 552
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
    "Content-Length": "47",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "ding_urllib_test",
    "X-Amzn-Trace-Id": "Root=1-62b2d47c-3dccfb5c5dbdff494e19bba3"
  },
  "json": null,
  "origin": "10.94.5.157, 58.213.34.25",
  "url": "http://httpbin.org/post"
}

常用的 HTTP 请求 的 Python 第三方模块

  • Requests(支持 HTTP/1.1)
  • HTTPX(也支持 HTTP/2):语法和 Requests 很像