如何使用http.client库实现带数据、代理和请求头的POST请求?
使用http.client实现等效于requests的POST请求
原requests实现的POST请求代码:
response = requests.post(url, data=data, verify=False, proxies=Proxy, headers=header_gen())
现有部分http.client代码,需完善以支持携带数据、代理及请求头:
conn = http.client.HTTPConnection(url.netloc) conn.request("POST", url.path, urllib.parse.urlencode({'username': 'admin', 'password': '123'}))
完善后的完整代码
import http.client import urllib.parse import ssl # 假设url是已通过urllib.parse.urlparse解析后的对象 # 从代理字典中提取代理地址与端口 proxy_info = urllib.parse.urlparse(Proxy['http'] if url.scheme == 'http' else Proxy['https']) proxy_host, proxy_port = proxy_info.hostname, proxy_info.port # 根据请求协议选择连接类型,处理verify=False逻辑 if url.scheme == 'https': # 创建不验证SSL证书的上下文 ssl_context = ssl._create_unverified_context() conn = http.client.HTTPSConnection(proxy_host, proxy_port, context=ssl_context) else: conn = http.client.HTTPConnection(proxy_host, proxy_port) # 编码POST表单数据 encoded_data = urllib.parse.urlencode(data).encode('utf-8') # 组装请求头:添加表单请求必需的Content-Type,合并自定义头 request_headers = header_gen() request_headers['Content-Type'] = 'application/x-www-form-urlencoded' request_headers['Host'] = url.netloc # 通过代理请求必须指定目标站点Host # 发送POST请求(包含查询参数) target_path = f"{url.path}?{url.query}" if url.query else url.path conn.request( method="POST", url=target_path, body=encoded_data, headers=request_headers ) # 获取并处理响应 response = conn.getresponse() response_content = response.read().decode('utf-8') conn.close()
关键细节说明
- 代理处理:创建连接时传入代理的主机和端口,同时通过
Host头指定目标站点域名,保证代理能正确转发请求。 - 证书跳过:HTTPS请求时用
ssl._create_unverified_context()实现verify=False的效果,跳过SSL证书校验。 - 数据编码:将表单数据编码为URL格式字节流,并设置
Content-Type头,这是表单POST请求的必要规范。 - 请求头合并:把自定义生成的请求头与标准必需头合并,确保请求格式合法。
内容的提问来源于stack exchange,提问作者middleStackoverflower
相关产品推荐
相关产品推荐

