python rest请求、requests

文章目录

测试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/#/

相关推荐
天天被压力1 分钟前
【A股分钟级高频数据完全手册 #04】指数分钟级行情数据接口:沪深指数Pro版最新分时取数
java·人工智能·python
日日大王学编程7 分钟前
2026主流AI Agent产品分类、核心差异与技术特性全解析
人工智能·后端·python
天天被压力11 分钟前
【A股分钟级高频数据完全手册 #03】股票历史1分钟K线数据接口怎么用:Pro版批量拉取与本地缓存
java·人工智能·python
zhanghaha131413 分钟前
C# 系列教程_7 判断语句(分支)保姆级精讲
开发语言·c#
apcipot_rain17 分钟前
C++转Java日记(02)
java·开发语言·c++
杜 硕40 分钟前
从零开始的C++生活——第七讲——02
开发语言·c++·生活
zhanghaha131442 分钟前
C# 系列教程_8 循环语句 保姆级精讲(面向新手)
开发语言·c#
麦麦麦当劳大王9 小时前
【油猴脚本】Boss直聘 岗位职责复制
开发语言·前端·javascript
starzy19909 小时前
深入理解Scala Map:从实现原理到工程实践
开发语言·后端·scala
只睡四小时10 小时前
Three.js Sub-tick:漏判 60.7%→0
开发语言·javascript·性能优化·ecmascript·游戏开发·three.js·碰撞检测