You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python的httpx模块发送包含下拉菜单JSON数据的POST请求

使用httpx发送带JSON Payload的POST请求

嘿,这事儿其实挺简单的,用httpx发送你提供的这种JSON格式的POST请求有几种常用方式,我给你一步步拆解:

最省心的方式:直接用json参数

httpx专门做了优化,提供了json参数来处理JSON payload场景——它会自动把Python字典序列化成JSON字符串,还会帮你设置正确的Content-Type: application/json请求头,完全不用自己操心格式问题。

完整代码示例:

import httpx

# 把你的JSON payload转成Python字典(注意布尔值要写成Python的False,不是JSON的false)
request_payload = {
    "token": "something",
    "events": [
        {
            "type": "impression_user_verify_phone",
            "properties": {
                "client_track_timestamp": 1652961971362,
                "impression_type": "modal",
                "location": "impression_friends",
                "accessibility_features": 524416,
                "accessibility_support_enabled": False,
                "client_performance_memory": 0,
                "client_send_timestamp": 1652961971397,
                "client_uuid": "HgBCFQ7xjA3RpVW54Kw13IABAAAKAAAA",
                "location_page": "impression_friends",
                "location_section": "impression_user_verify_phone",
                "rendered_locale": "tr"
            }
        }
    ]
}

# 替换成你实际要请求的目标站点URL
target_url = "https://your-target-site.com/your-api-endpoint"

# 发送POST请求
response = httpx.post(target_url, json=request_payload)

# 可选:验证请求结果
print(f"响应状态码: {response.status_code}")
print("响应内容:")
print(response.json())

手动序列化方式(适合自定义需求)

如果你需要对JSON序列化做特殊设置(比如格式化输出、处理特殊数据类型),可以用json.dumps()手动序列化,再通过data参数传递,记得手动设置Content-Type请求头:

import httpx
import json

request_payload = { ... } # 和上面的字典一致

# 自定义序列化选项,比如添加缩进让输出更易读
serialized_payload = json.dumps(request_payload, indent=2)

response = httpx.post(
    target_url,
    data=serialized_payload,
    headers={"Content-Type": "application/json"}
)

额外实用提示

  • 如果目标站点需要身份验证或其他自定义请求头,直接在httpx.post()里添加headers参数即可,比如headers={"Authorization": "Bearer your-auth-token"}
  • 可以设置超时时间避免请求挂起,比如timeout=10(单位为秒)
  • 如果需要多次请求复用连接,推荐用httpx.Client()上下文管理器,性能会更好:
    with httpx.Client() as client:
        response = client.post(target_url, json=request_payload)
    

内容的提问来源于stack exchange,提问作者Kervn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:53:12