如何在Python中用requests/http.client实现指定curl POST请求
问题核心偏差
你写的代码和原curl请求存在3个关键错误,会直接导致调用失败:
- 请求方法不匹配:原curl是
POST请求,你错写成了GET - 参数传递逻辑错误:原curl的参数是放在JSON格式的请求体中传递,不是拼接在URL后的查询参数里,且参数名、类型均不匹配(原参数是数组类型的
ProductNames,你错写成单值ProductName) - 客户端用法错误:
http.client.HTTPSConnection初始化时仅需要传入域名+端口,不需要传入完整接口路径,路径需要在发起请求时单独指定;同时你缺失了必填的Content-Type: application/json请求头
Swagger展示的基础路径就是接口的完整请求地址,不需要额外拼接查询参数,所有参数按照接口定义放在请求体传递即可。
推荐实现(简洁规范版)
优先使用requests库(Python接口调用的通用事实标准,先执行pip install requests安装),代码完全对齐原curl逻辑:
import requests url = "https://api.aws.com:443/api/rep/grep" headers = { "Accept": "application/json", "Authorization": "xxxx" # 替换为实际鉴权值 } # 请求体和curl的-d参数完全对应 payload = { "ProductNames": ["PReport"], "SearchType": "FullAddress", "FullAddress": "123 Main Street, New York, 10001", "ReferenceId": "" } # 发起POST请求,json参数会自动做JSON序列化、设置Content-Type头 response = requests.post(url, headers=headers, json=payload) # 查看响应状态码 print(response.status_code) # 解析JSON响应结果 print(response.json())
标准库实现(无第三方依赖版)
如果不想安装第三方库,使用原生http.client的正确实现如下:
import http.client import json # 初始化连接仅需传入域名和端口 conn = http.client.HTTPSConnection("api.aws.com", 443) headers = { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "xxxx" # 替换为实际鉴权值 } payload = json.dumps({ "ProductNames": ["PReport"], "SearchType": "FullAddress", "FullAddress": "123 Main Street, New York, 10001", "ReferenceId": "" }) # 发起POST请求,接口路径单独传入,请求体放在body参数位 conn.request("POST", "/api/rep/grep", body=payload, headers=headers) res = conn.getresponse() # 读取并解析响应 result = json.loads(res.read().decode("utf-8")) print(res.status) print(result) conn.close()
内容的提问来源于stack exchange,提问作者kms
相关产品推荐
相关产品推荐

