如何将curl命令的JSON响应写入文件?API请求验证错误排查
解决API证书导入的验证错误问题
错误根源分析
API返回的验证错误明确要求请求包含两个主体部分:证书信息和证书数据,当前的curl命令与requests代码均存在格式或语法问题,导致请求结构不符合API要求。
curl命令及Python调用修复
原问题点
- 命令语法错误:
--header参数间缺少空格,-F参数的引号与空格格式混乱,导致请求头和表单字段解析失败。 - 输出捕获错误:
os.system(cmd)仅返回命令退出状态码(0为成功,非0为失败),并非API返回的JSON响应,无法通过json.dump写入有效数据。
修正后的代码
# 修正语法后的curl命令(注意参数间的空格和引号格式) cmd='curl -k -u admin:admin -X POST \ --header "Content-Type: multipart/mixed" \ --header "Accept: application/json" \ -F "myPartnm1=@sftprest;type=application/json" \ -F "myPartname2=@sftppvteopenkey;type=application/json/oc-stream" \ http://cdrteo456.serms.com:4456/api/v/cert'
import subprocess import json # 使用subprocess捕获curl的标准输出 result = subprocess.run(cmd, shell=True, capture_output=True, text=True) if result.returncode == 0: # 将API返回的JSON写入文件 with open("dff.json", "w") as f: f.write(result.stdout) # 读取并解析JSON数据 with open("dff.json") as f1: data = json.load(f1) print(data.get('id')) else: print(f"curl命令执行失败: {result.stderr}")
requests代码修复
原问题点
- 请求头错误:重复定义
Content-Type,且手动设置multipart/mixed多余——requests发送files参数时会自动生成包含boundary的正确请求头,手动设置会破坏自动生成的结构。 - files参数格式错误:错误地将
type参数拼接到文件路径中,正确做法是通过元组指定文件对象、文件名和Content-Type。 - 文件路径拼写错误:
sftppvteopenkeyopt/tr5/new.pem应为sftppvteopenkey/opt/tr5/new.pem(与curl命令中的路径对应)。
修正后的代码
import requests # 无需手动设置Content-Type,requests会自动处理 headers = { 'Accept': 'application/json', } # 正确的files参数格式:(字段名, (文件名, 文件对象, Content-Type)) files = { 'myPartnm1': ('sftprest', open('sftprest/opt/tr5.txt', 'rb'), 'application/json'), 'myPartname2': ('sftppvteopenkey', open('sftppvteopenkey/opt/tr5/new.pem', 'rb'), 'application/json/oc-stream'), } response = requests.post( 'http://cdrteo456.serms.com:4456/api/v/cert', headers=headers, files=files, verify=False, auth=('admin', 'admin') ) # 打印响应内容排查问题 print(response.status_code) print(response.json())
额外注意事项
- 确认表单字段名
myPartnm1和myPartname2与API文档要求完全一致(注意拼写,比如myPartnm1是否应为myPartname1)。 - 确保
sftprest/opt/tr5.txt和sftppvteopenkey/opt/tr5/new.pem文件路径正确,文件存在且可读。 - 若API明确要求
multipart/mixed而非默认的multipart/form-data,可通过requests的PreparedRequest手动构造请求头,但优先依赖requests的自动处理。
内容的提问来源于stack exchange,提问作者Grey
相关产品推荐
相关产品推荐

