Python urllib3 发送请求完全指南

Python urllib3 发送请求完全指南 urllib3 是 Python 中最流行的 HTTP 客户端库之一相比内置的urllib它更简洁、更强大、更易用。本文从零开始覆盖日常开发中 90% 的请求场景。一、为什么选 urllib3对比项urllib内置requests第三方urllib3上手难度较高极低低连接池需手动管理内置内置核心优势线程安全否否是性能一般一般更优requests 底层其实就是用 urllib3 实现的。学会 urllib3等于理解了 requests 的内核。二、安装pipinstallurllib3三、GET 请求 —— 最基础的用法importurllib3 httpurllib3.PoolManager()# 创建连接池推荐resphttp.request(GET,https://httpbin.org/get)print(resp.status)# 200print(resp.data)# b{args:{}, ...}print(resp.headers)# 响应头关键点PoolManager()内部维护连接池复用 TCP 连接性能远好于每次新建连接响应数据是bytes需要解码resp.data.decode(utf-8)四、带参数的 GET 请求resphttp.request(GET,https://httpbin.org/get,fields{key:value,page:1}# 自动拼接 ?keyvaluepage1)print(resp.data.decode(utf-8))等价于手动拼接 URLfromurllib.parseimporturlencode urlhttps://httpbin.org/get?urlencode({key:value})但用fields更安全urllib3 会自动处理编码避免特殊字符导致的问题。五、POST 请求 —— 三种常见场景5.1 表单提交application/x-www-form-urlencodedresphttp.request(POST,https://httpbin.org/post,fields{username:admin,password:123456})5.2 JSON 提交application/jsonimportjson resphttp.request(POST,https://httpbin.org/post,bodyjson.dumps({username:admin}),headers{Content-Type:application/json})5.3 上传文件multipart/form-datawithopen(photo.jpg,rb)asf:resphttp.request(POST,https://httpbin.org/post,fields{file:(photo.jpg,f,image/jpeg)})格式(文件名, 文件对象, MIME类型)六、自定义请求头resphttp.request(GET,https://api.example.com/data,headers{User-Agent:my-app/1.0,Authorization:Bearer xxxxxxx})常见坑User-Agent必加否则很多接口会直接拒绝尤其是反爬场景。七、超时设置生产环境必加resphttp.request(GET,https://httpbin.org/delay/5,timeout3.0# 3秒超时超时抛出 urllib3.exceptions.TimeoutError)也可以分别设置连接超时和读取超时resphttp.request(GET,https://example.com,timeout(3.0,10.0)# (连接超时, 读取超时))八、异常处理 —— 别让程序崩溃importurllib3fromurllib3.exceptionsimportHTTPError,TimeoutError,MaxRetryError httpurllib3.PoolManager(retries3)# 自动重试3次try:resphttp.request(GET,https://httpbin.org/status/500)resp.raise_for_status()# 非200状态码抛出 HTTPErrorexceptTimeoutError:print(请求超时)exceptHTTPErrorase:print(fHTTP错误:{e.response.status})exceptMaxRetryError:print(重试次数耗尽)最常用的三个异常异常触发场景TimeoutError超时未响应HTTPError非 2xx 状态码MaxRetryError重试耗尽仍失败九、进阶连接池复用性能关键httpurllib3.PoolManager(num_pools10,# 最大连接池数量maxsize10,# 每个池最大连接数retries3,# 自动重试次数timeout5.0)# 复用同一个 http 对象发送多个请求r1http.request(GET,https://api.example.com/users)r2http.request(GET,https://api.example.com/orders)千万不要每次请求都urllib3.PoolManager()那等于每次都新建连接池失去了 urllib3 最大的性能优势。十、完整实战示例调用一个 REST APIimporturllib3importjson httpurllib3.PoolManager(timeout10.0,retries3)defcall_api(endpoint,dataNone,methodGET):urlfhttps://api.example.com{endpoint}kwargs{method:method,headers:{Content-Type:application/json,Authorization:Bearer your_token_here}}ifdata:kwargs[body]json.dumps(data)try:resphttp.request(url,**kwargs)resp.raise_for_status()returnresp.data.decode(utf-8)excepturllib3.exceptions.HTTPErrorase:print(fAPI返回错误:{e.response.status}-{e.response.data})returnNoneexcepturllib3.exceptions.TimeoutError:print(请求超时)returnNone# 调用resultcall_api(/users,data{name:zhangsan},methodPOST)print(result)总结速查表需求核心参数GET 请求http.request(GET, url)带参数 GETfields{k: v}POST 表单fields{k: v}POST JSONbodyjson.dumps(data),headers{Content-Type: application/json}上传文件fields{file: (name, fp, type)}自定义头headers{Key: Value}超时timeout3.0自动重试PoolManager(retries3)urllib3 不花哨但足够可靠。掌握以上内容日常接口调用绰绰有余。