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

如何在Python中实现带请求头和请求数据的curl POST请求?

问题分析

你的代码逻辑不存在致命错误,运行后无输出是因为你没有读取并打印接口返回的响应内容:urllib.request.urlopen执行完成后只会返回响应对象,不会主动输出接口返回的数据。
另外你代码中手动添加Content-Length请求头的操作是多余的,urllib传入POST数据时会自动计算并添加该头字段,无需手动处理。同时缺少异常捕获逻辑,若接口返回4xx/5xx错误状态码,urllib会直接抛出异常,你当前的代码无法捕获查看具体错误信息。

修正后的urllib版本代码

import urllib.request
import json

body = {"email": "xxx@xx.com","password": "xxx"}
myurl = "https://xx.com/login"

req = urllib.request.Request(myurl, method='POST')
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')

try:
    response = urllib.request.urlopen(req, jsondataasbytes)
    # 读取解码响应内容
    res_content = response.read().decode('utf-8')
    # 打印返回结果
    print("响应状态码:", response.getcode())
    print("响应内容:", res_content)
    # 若接口返回JSON格式可直接转字典处理
    # res_json = json.loads(res_content)
except urllib.error.HTTPError as e:
    print("请求错误,状态码:", e.code)
    print("错误详情:", e.read().decode('utf-8'))
except Exception as e:
    print("其他异常:", str(e))

更简洁的requests库实现(可选)

如果允许使用第三方库,requests实现相同逻辑的代码更简洁,不需要手动处理编码、头字段等细节:

import requests

body = {"email": "xxx@xx.com","password": "xxx"}
myurl = "https://xx.com/login"

response = requests.post(myurl, json=body)
print("响应状态码:", response.status_code)
print("响应内容:", response.text)
# 直接获取JSON格式返回:response.json()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:18:03