Python标准库http.client发送HTTP请求

48 阅读1分钟

微信图片_20230808094553.pnghttp.client是Python标准库中用于HTTP/1.1协议通信的低级模块,虽然不如requests库便捷,但在资源受限环境或需要精细控制HTTP连接时非常有用。以下是详细使用指南:

1. 基础GET请求****

python

 from http.client import HTTPConnection, HTTPSConnection
 import urllib.parse
  
 # 创建HTTP连接
 conn = HTTPConnection("www.example.com", 80, timeout=5)
 try:
 # 发送GET请求
 conn.request("GET", "/index.html")
 response = conn.getresponse()
  
 # 读取响应
 print(f"状态码: {response.status}")
 print(f"原因: {response.reason}")
 print(f"响应头:\n{response.getheaders()}")
 print(f"响应体:\n{response.read().decode('utf-8')}")
 finally:
 conn.close()

2. HTTPS请求与参数处理****

python

 # HTTPS连接示例
 conn = HTTPSConnection("api.example.com", 443)
 params = urllib.parse.urlencode({'q': 'python', 'page': 1})
 try:
 conn.request("GET", f"/search?{params}")
 response = conn.getresponse()
 print(response.read().decode())
 finally:
 conn.close()

虽然http.client功能较为底层,但它提供了对HTTP协议的完全控制,适合需要优化每字节传输或实现特殊协议交互的场景。对于大多数应用场景,建议使用更高级的requests库,但在嵌入式系统或资源受限环境中,http.client是轻量级解决方案。