Python requests库的应用
前言:
requests 是一个用于发送 HTTP 请求的 Python 第三方库,它简化了与 Web 服务交互的过程。requests 库以其简单易用、功能强大而闻名,使得处理 HTTP 请求变得非常直观。
web 接口是我自个写的,看个意思就行
python实操:
1、安装requests库
pip install requests
2、get 请求
import requests
import json
# get 请求
getUrl = "http://127.0.0.1:8080/getStudentInfo"
payload = {'id': '1'}
res2 = requests.get(getUrl, payload).json()
print(json.dumps(res2, indent=4, ensure_ascii=False))
解释:
- 使用
requests.get()
发送 GET 请求,并将payload
自动作为查询参数附加到 URL 上。 .json()
方法会将响应体解析为 JSON 对象(前提:服务器返回的是合法 JSON)。- 使用
json.dumps()
将 Python 字典格式化为美观的 JSON 字符串:indent=4
表示缩进 4 个空格,使结构更清晰。ensure_ascii=False
确保中文等非 ASCII 字符不被转义。
3、post 请求
import requests
import json
# post 请求
postUrl = "http://127.0.0.1:8080/addStudentInfoTo1"
data = {
"id": 1000,
"classId": 10,
"name": "嘻哈",
"age": 11,
"sex": "男",
"idNumber": "445221199602104132",
"birthDay": "1996-01-10",
"createTime": "2025-05-06T17:35:00"
}
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
}
res = requests.post(postUrl, json=data, headers=header)
res_json = json.dumps(res.json(), indent=4, ensure_ascii=False)
print(res_json)
解释:
- 使用
requests.post()
发送 POST 请求,并将 data、header分别作为请求参数和头部参数添加。 - 构建一个字典对象
data
,表示你要提交给服务器的数据。 - 设置请求头信息header,模拟浏览器访问,有些后端接口会验证 User-Agent。
json=data
:自动将字典转换为 JSON 格式,并设置Content-Type: application/json
。headers=header
:添加自定义请求头。res.json()
:将响应内容解析为 Python 字典。json.dumps(...)
:将字典格式化为美观的 JSON 字符串打印出来。indent=4
:缩进 4 个空格,提升可读性。ensure_ascii=False
:防止中文字符被转义成 \uXXXX,适合调试和展示。
4、文件上传/下载
上传:
import requests
# 文件上传
url = 'http://127.0.0.1:8080/api/files/upload'
file_path = '../resources/test.log'
try:
# 以二进制只读模式打开文件。
# 'r' 表示读取(read);
# 'b' 表示二进制(binary),适合用于所有类型的文件(如图片、日志、视频等),避免编码问题。
with open(file_path, 'rb') as f:
# 可自定义文件名上传,这里定义同名的test.log
files = {'file': ('test.log', f)}
response = requests.post(url, files=files, timeout=10)
print(f"Status Code: {response.status_code}")
print("Response Text:", response.text)
except FileNotFoundError:
print("错误:文件未找到,请检查文件路径。")
except requests.exceptions.ConnectionError:
print("错误:无法连接到目标服务器,请确认服务是否启动。")
except requests.exceptions.RequestException as e:
print(f"请求过程中发生错误: {e}")
下载:
import requests
# 文件下载
url = 'http://127.0.0.1:8080/api/files/download/test2.log'
file_path = '../resources/test3.log'
response = requests.get(url, stream=True, timeout=10)
if response.status_code == 200:
with open(file_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
print("下载完成")
else:
print("下载失败")
java服务端代码:
https://gitee.com/a_cloud/python_springboot_demo.git
python客户端代码:
https://gitee.com/a_cloud/self_study_python.git
评论区