文章目录
测试url可以自己造,这里演示用httpbin网站提供的,比较方便。
安装依赖
python
pip install requests
get请求
python
import requests
# 目标 URL (这是一个测试用的接口,返回请求信息)
url = "https://httpbin.org/get"
# 定义 URL 参数 (字典格式)
params = {
"page": "1",
"limit": "10",
"search": "python"
}
# 定义请求头 (模拟浏览器,防止部分网站反爬虫)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
try:
# 发送 GET 请求
# params 参数会自动拼接到 url 后面
response = requests.get(url, params=params, headers=headers, timeout=5)
# 检查状态码是否为 200
if response.status_code == 200:
print("✅ 请求成功!")
# 获取 JSON 格式的数据
data = response.json()
print("📄 返回数据:", data)
else:
print(f"❌ 请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"❌ 发生异常: {e}")
post请求
python
import requests
url = "https://httpbin.org/post"
# 表单数据
payload = {
"username": "admin",
"password": "123456",
"remember": "true"
}
try:
response = requests.post(url, data=payload, timeout=5)
if response.status_code == 200:
print("✅ 表单提交成功!")
json_data = response.json()
# 查看服务器接收到的 form 数据
print("📝 服务器接收到的表单:", json_data.get('form'))
else:
print(f"❌ 提交失败: {response.status_code}")
except Exception as e:
print(f"❌ 发生错误: {e}")
发送带file文件的请求
主要有两种形式:
1、表单
2、二进制
注意发送前要用json.dumps()序列化下。
发送带file文件的请求-1、表单
python
import requests
import json
url = "https://httpbin.org/post" # 测试接口
# 1. 准备 JSON 数据结构
json_payload = {
"user_id": 12345,
"description": "这是文件的元数据",
"tags": ["test", "python"]
}
# 2. 准备文件流 (以二进制读取)
# 假设我们有一个名为 'test.jpg' 的文件
try:
with open('test.jpg', 'rb') as f:
# files 字典的值可以是元组: ('文件名', 文件对象, 'MIME类型')
files = {
'file_field': ('test.jpg', f, 'image/jpeg')
}
# data 字典的值必须是字符串,所以要把 json 对象转成字符串
data = {
'json_data': json.dumps(json_payload)
}
# 3. 发送请求
# 注意:不要手动设置 Content-Type,requests 会自动生成 boundary
response = requests.post(url, files=files, data=data)
if response.status_code == 200:
print("✅ 上传成功")
# 打印服务器收到的数据以验证
res_json = response.json()
print("📄 收到的表单数据:", res_json.get('form'))
print("📦 收到的文件信息:", res_json.get('files'))
else:
print(f"❌ 失败: {response.status_code}")
except FileNotFoundError:
print("❌ 文件未找到,请确保目录下有 test.jpg")
发送带file文件的请求-2、二进制
python
import requests
import json
url = "https://httpbin.org/post"
json_payload = {
"mode": "stream",
"version": "1.0"
}
try:
with open('test.jpg', 'rb') as f:
# 1. 将 JSON 转为字符串放入请求头
# 注意:HTTP 头通常不支持复杂嵌套的 JSON,建议扁平化,或者确保后端能解析
headers = {
"Content-Type": "application/octet-stream", # 声明是二进制流
"X-Json-Meta": json.dumps(json_payload) # 自定义头存放 JSON
}
# 2. 直接将文件对象传给 data
response = requests.post(url, data=f, headers=headers)
if response.status_code == 200:
print("✅ 流上传成功")
# 查看请求体长度是否匹配
print(f"📊 发送字节数: {len(response.request.body)}")
else:
print(f"❌ 失败: {response.status_code}")
except FileNotFoundError:
print("❌ 文件未找到")
其他
文档
httpbin测试url网站:
https://httpbin.org/#/