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

如何用Python发送含无效JSON的HTTP POST请求?

解决Python发送含无效JSON的POST请求问题

问题核心

你遇到的问题本质是Python代码里的无效JSON字符串和curl发送的内容不一致,导致服务器解析逻辑触发了不同的错误分支;另外requests库的json参数会自动序列化合法JSON,无法直接生成无效格式,但data参数支持发送原始字符串,只要内容完全匹配curl的请求体即可。

解决方法

1. 同步请求体内容

直接复制curl命令中-d后的原始字符串到Python,确保所有符号(括号、引号)完全一致:
比如curl里的-d '{"email":"user2@user2.com","password":"testpasswd}}}',对应的Python字符串应为:

INVALID_JSON = '''{"email":"user2@user2.com","password":"testpasswd}}}'''

2. 使用requests库发送请求

保持用data参数传递原始字符串,并显式设置Content-Type头,代码示例:

import requests

BASE_URL = "http://[my IP]:3003"
INVALID_JSON = '''{"email":"user2@user2.com","password":"testpasswd}}}'''

def test_signup_with_invalid_json():
    url = BASE_URL + '/signup'
    headers = {"Content-Type": "application/json"}
    resp = requests.post(url, data=INVALID_JSON, headers=headers)
    print(resp, resp.text)

test_signup_with_invalid_json()

3. 用http.client发送底层请求(备选)

如果requests存在隐藏的内容处理,可直接用http.client发送原始请求,完全模拟curl的行为:

import http.client

def test_invalid_json():
    conn = http.client.HTTPConnection("[my IP]", 3003)
    payload = '''{"email":"user2@user2.com","password":"testpasswd}}}'''
    headers = {'Content-Type': 'application/json'}
    conn.request("POST", "/signup", payload, headers)
    
    res = conn.getresponse()
    print(f"{res.status} {res.reason}")
    print(res.read().decode("utf-8"))
    
    conn.close()

test_invalid_json()

验证建议

可以用抓包工具(如Wireshark、Fiddler)对比curl和Python发送的请求,确认请求体内容、HTTP头完全一致,避免因字符串转义或编码差异导致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:32:38