import hashlib
import hmac
import http.client
import json
import email.utils
from datetime import datetime, timezone
输入数据
input_data = {
"url": "https://ddm.sxycpc.com:10066/file/mdoc/c4ff1e82-14de-4181-8736-60a885d86b9c/057fb5b0-1a4d-45aa-99c8-a2f6857d3f09/6625d9e8f02fc79e369dcb11/20240815/3gckfB2M5N5u7BbTfL7Y5scE3B5qcW51fUeL5d2Kcj6z90ej2yfK0n007C6n210y.docx?attname=%E4%B8%80%E4%BA%8B%E4%B8%80%E8%AE%AE.docx&e=1723707303&token=storage:gZCO4pQLicGKBCBE6fwkuyF2LH8",
"filename": "一事一议.docx",
"app_id": "SX20240814AWWMCJ",
"app_key": "WHNrdVQBiirNRCehbeJVUoRRppPcDvyq"
}
提取输入参数
url = input_data["url"]
filename = input_data["filename"]
app_id = input_data["app_id"]
app_key = input_data["app_key"].strip().encode('utf-8') # 确保 app_key 是字节串
准备请求负载
payload = json.dumps({
"url": url,
"filename": filename
}).encode('utf-8') # 确保负载为字节串
获取当前的 RFC1123 格式的日期时间,使用 UTC 时间 current_time = email.utils.formatdate(timeval=None, localtime=False, usegmt=True) content_md5 = hashlib.md5(payload).hexdigest() # 计算 MD5 content_type = "application/json"
计算签名 string_to_sign = app_key + content_md5.encode('utf-8') + content_type.encode('utf-8') + current_time.encode('utf-8') signature = hmac.new(app_key, string_to_sign, hashlib.sha1).hexdigest()
生成 Authorization 头 authorization_header = f"WPS-2:{app_id}:{signature}"
准备请求头
headers = {
'Date': current_time,
'Content-Md5': content_md5,
'Content-Type': content_type,
'Authorization': authorization_header
}
创建 HTTPS 连接并发送请求 conn = http.client.HTTPSConnection("solution.wps.cn") conn.request("POST", "/api/developer/v1/office/convert/to/pdf", payload, headers)
获取响应 res = conn.getresponse() data = res.read()
处理输出
output = {
"code": res.status, # HTTP 状态码
"message": "InvalidSignature" if res.status != 200 else "Success",
"hint": data.decode("utf-8"),
"extra": f"signature not match. expected: {authorization_header}, actual: {data.decode('utf-8')}"
}
输出结果 print(json.dumps(output, indent=2))