page contents

写 Python 发接口最烦的是什么?

同步阻塞、不支持 HTTP/2、异步要换库、文件上传繁琐、Cookie 管理麻烦、SSL 自定义配置绕来绕去,高并发接口测试、爬虫、自动化脚本写起来处处受限!

attachments-2026-08-FbToqZUg6a7296a50ee67.png绝对是 requests 短板一堆!

同步阻塞、不支持 HTTP/2、异步要换库、文件上传繁琐、Cookie 管理麻烦、SSL 自定义配置绕来绕去,高并发接口测试、爬虫、自动化脚本写起来处处受限!

今天给大家推荐 Python 现代化全能 HTTP 库:httpx

一行代码替代 requests,同步/异步双支持、HTTP/1.1+HTTP/2、自动连接池、超时控制完善,接口调试、自动化测试、爬虫全能扛!

httpx 是当下 Python 最主流现代化网络请求库,兼容 requests 写法,同时补齐同步异步短板,是接口自动化、爬虫、服务间调用神器。

主打:兼容 requests 语法、同步异步一套库、HTTP2 支持、完整类型提示、优雅超时/重试/证书配置,大幅减少网络请求冗余代码。

核心优势

兼容 requests 写法,零基础无缝迁移

同时支持同步请求 + 异步 async 异步请求,不用切换第三方库

原生支持 HTTP/1.1、HTTP/2,访问现代接口更快

自带智能连接池,高频请求性能远超原生 requests

完善超时、重试、代理、SSL、Cookie、会话持久化

内置类型注解,IDE 自动提示,减少代码报错

文件上传、表单、JSON 参数语法极简,接口调试更省心

适用场景

自动化测试:批量调用后端接口、压测前置请求、接口返回校验

爬虫开发:同步轻量爬虫、高并发异步爬虫

后端服务:Python 服务调用第三方 http 接口、微服务互通

脚本工具:批量拉取数据库配套接口数据、第三方API对接

定时任务:稳定持久会话,减少重复建连接损耗

⚙️ 安装方式

非标准内置库,一键 pip 安装

pip install httpx

# 如需支持 HTTP/2 额外安装依赖

pip install httpx[http2]

# 异步高性能推荐完整包

pip install httpx[all]

导入直接使用:

import httpx

# 异步专用

import asyncio

高频实战代码

1、同步GET请求(完美替代requests,带参数打印)

import httpx

from pprint import pprint

 

# 1.基础get请求

def sync_get():

    url ="https://httpbin.org/get"

    params ={"username":"test","page":1,"size":10}

    headers ={"User-Agent":"httpx-test/1.0"}

 

    resp = httpx.get(url, params=params, headers=headers, timeout=10)

# 状态码校验

    resp.raise_for_status()

# 格式化打印接口返回json,搭配上文pprint

print("接口返回数据:")

    pprint(resp.json())

print("响应状态码:", resp.status_code)

print("响应头:", resp.headers)

 

sync_get()

2、同步POST JSON请求(接口测试最常用)

import httpx

from pprint import pprint

 

def sync_post_json():

    url ="https://httpbin.org/post"

    json_data ={

"user_id":1001,

"info":{"name":"测试用户","tags":["接口测试","httpx"]}

}

# 持久会话,复用连接,多次请求推荐用Client

with httpx.Client(timeout=15)as client:

        resp = client.post(url, json=json_data)

        pprint(resp.json())

 

sync_post_json()

3、异步请求(高并发批量调用接口,压测/爬虫必备)

import httpx

import asyncio

from pprint import pprint

 

async def async_request():

    url ="https://httpbin.org/get"

    async with httpx.AsyncClient(http2=True)as client:

        resp = await client.get(url, params={"async":"true"})

        pprint(resp.json())

 

# 执行异步函数

asyncio.run(async_request())

4、文件上传、表单提交场景

import httpx

 

def upload_file():

    url ="https://httpbin.org/post"

# 上传本地文件

    files ={"file": open("test.txt","rb")}

    data ={"desc":"上传测试文件"}

    resp = httpx.post(url, files=files, data=data)

print(resp.json())

 

upload_file()

5、自定义代理、Cookie、请求重试

import httpx

from httpx importLimits

 

def proxy_cookie_demo():

# 全局配置:连接限制、代理、持久cookie

    transport = httpx.HTTPTransport(proxy="http://127.0.0.1:7890")

    limits =Limits(max_connections=10)

    cookies ={"token":"abc123456"}

 

with httpx.Client(transport=transport, limits=limits, cookies=cookies)as client:

        resp = client.get("https://httpbin.org/cookies")

print(resp.json())

 

proxy_cookie_demo()

 

核心方法简单说明

同步系列

httpx.get(url):GET 请求

httpx.post(url,json=xxx):POST JSON接口

httpx.Client():同步会话对象,复用连接,高频请求必用

resp.json():直接解析返回json字典

resp.text:原始文本响应

resp.raise_for_status():非200状态码直接抛异常,自动校验接口

异步系列

httpx.AsyncClient():异步会话,高并发场景

awaitclient.get():异步请求必须加await

http2=True:开启HTTP2协议加速请求

通用参数

timeout=10:全局超时时间,防止接口卡死

headers={}:自定义请求头

params={}:url拼接查询参数

cookies={}:携带登录凭证

- verify=False:关闭ssl证书校验

日常踩坑提醒

同步代码不要混用 AsyncClient,异步代码必须搭配 await + asyncio.run(),否则报错

频繁请求务必使用 Client / AsyncClient,不要每次直接 httpx.get(),会频繁创建销毁连接,性能极差

关闭SSL校验仅用于内网测试环境,线上生产环境禁止 verify=False

requests 代码迁移仅需把 import requests 改成 import httpx,大部分方法无需改动,迁移成本极低

异步场景下无法直接使用普通同步函数,所有网络请求都要写async函数

若接口返回非标准JSON,resp.json()会抛异常,改用 resp.text 查看原始返回排查问题

字符串保存返回结果用法

import httpx

import pprint

 

resp = httpx.get("https://httpbin.org/get")

res_str = pprint.pformat(resp.json(), indent=2)

# 写入日志文件

with open("api_log.txt","w", encoding="utf-8")as f:

    f.write(res_str)

总结

如果你平时写 Python 接口自动化、爬虫、第三方API对接、批量调用服务接口,直接替换老旧 requests! httpx 语法简单、同步异步一体、支持HTTP2、自带连接池、类型提示完善,大幅简化网络请求代码,调试、并发场景体验碾压 requests,属于后端/测试开发必掌握网络库! 建议收藏,写接口请求直接复制模板即用!

 更多相关技术内容咨询欢迎前往并持续关注好学星城论坛了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

  • 发表于 2026-08-05 09:49
  • 阅读 ( 34 )
  • 分类:Python开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

2307 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. Pack 2307 文章
  3. 小柒 2228 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章