需求
- 调用get label 接口
- 将接口返回的base64文件转换成pdf
- 文件命名用接口返回值的单号命名保存再指定的文件夹重
实现代码
import requests
import base64
import os
import json url = "http://releasud.com/api/label/LableApi/GalProcess"
headers = {"Content-Type": "application/json","token": "MjAxNjA4MDkxBRDJBOThFNjVCMDBDNTc2OURCM0U3NA=="
}
body = {"TrackNumber": "F7532425032000IA","IsNeedLable": True
}try:response = requests.post(url, json=body, headers=headers)response.raise_for_status() response_data = response.json()print("完整响应内容:\n", json.dumps(response_data, indent=2, ensure_ascii=False))if "Data" not in response_data:print("错误:响应中缺少Data字段")exit()data = response_data["Data"]label_encoded = data.get("Label")channel_trace_id = data.get("ChannelTraceId")msg = data.get("Msg", "无附加信息")if label_encoded is None:print(f"错误:标签未生成,原因 -> {msg}")exit()if channel_trace_id is None:print("错误:ChannelTraceId为空")exit()try:label_pdf = base64.b64decode(label_encoded)except Exception as e:print(f"Base64解码失败: {e}")exit()os.makedirs("Label", exist_ok=True)file_path = os.path.join("Label", f"{channel_trace_id}.pdf")with open(file_path, "wb") as f:f.write(label_pdf)print(f"文件保存成功: {file_path}")except ValueError as e: print(f"错误:响应不是有效的JSON格式 -> {e}")print("原始响应内容:", response.text)
except requests.exceptions.RequestException as e:print(f"请求失败: {e}")
except KeyError as e:print(f"响应字段缺失: {e}")
except Exception as e:print(f"未知错误: {e}")
运行结果:
D:\PYTHON-学习\邮政接口压力测试脚本\pythonProject1\.venv\Scripts\python.exe D:\PYTHON-学习\邮政接口压力测试脚本\pythonProject1\huoqu_Label.py
完整响应内容:{"Status": 1,"Data": {"Label": null,"Msg": "F7532425032000IA未查询到单号信息!","ChannelTraceId": null,"ServiceProviderName": null},"ErrCode": null,"ErrMsg": null
}
错误:标签未生成,原因 -> F7532425032000IA未查询到单号信息!进程已结束,退出代码为 0