安装 httpx 库
pip install httpx
同步请求示例
import httpx
url = "https://www.example.com"
# 发送同步 GET 请求
response = httpx.get(url)
# 打印响应内容
print(response.text)
异步请求示例
import asyncio
import httpx
url = "https://www.example.com"
async def fetch_data():
async with httpx.AsyncClient() as client:
# 发送异步 GET 请求
response = await client.get(url)
return response.text
# 异步运行
async def main():
result = await fetch_data()
print(result)
# Python 3.7及以上版本可以使用以下方式运行异步代码
asyncio.run(main())
发送带参数的请求
import httpx
url = "https://www.example.com"
params = {"key1": "value1", "key2": "value2"}
# 发送 GET 请求带参数
response = httpx.get(url, params=params)
# 打印响应内容
print(response.text)
发送 JSON 数据的请求
import httpx
url = "https://www.example.com"
json_data = {"key1": "value1", "key2": "value2"}
# 发送 POST 请求带 JSON 数据
response = httpx.post(url, json=json_data)
# 打印响应内容
print(response.text)
添加请求头
import httpx
url = "https://www.example.com"
headers = {"User-Agent": "MyApp/1.0"}
# 发送请求带自定义请求头
response = httpx.get(url, headers=headers)
# 打印响应内容
print(response.text)
这只是 httpx 的一小部分功能,该库还支持超时控制、文件上传、代理设置、认证等多种高级功能。你可以查阅 [httpx 的官方文档](https://www.python-httpx.org/) 以获取更详细的信息。
转载请注明出处:http://www.zyzy.cn/article/detail/269/Python3