Python Requests POST发送XML在Debian服务器编码异常求助
跨平台XML POST请求编码问题排查求助
我编写了一段使用Python requests模块通过POST方法向API发送XML的脚本,该脚本在Windows测试机上运行正常,但部署到Debian生产服务器时始终出现解析错误。将XML文件编码改为ANSI后,脚本在Debian服务器上即可正常运行。
我判断这是编码问题,已按要求配置UTF-8相关设置:以UTF-8编码读取XML模板文件,请求头中设置Content-Type: application/xml; charset=utf-8,XML声明也指定UTF-8编码。在Debian服务器上打印payload字符串显示正常,但问题仍未解决。
目前只能以ANSI编码作为临时 workaround,但希望实现Windows与Debian跨平台一致的解决方案,同时支持德语特殊字符,请求协助排查。
相关代码片段
# prepare XML for API call url = "https://myurl.com/api/method" # use XML template and replace some wildcards payloadTemplate = open("message.xml", encoding="utf-8") payload = payloadTemplate.read() payload = str(payload % (sessiontoken, accountName, key, userId)) headers = { 'X-XYZ-API-COMPATIBILITY-LEVEL': '1234', 'X-XYZ-API-CALL-NAME': 'methodname', 'X-XYZ-API-SITEID': '11', 'Content-Type': 'application/xml; charset=utf-8' } # send request response = requests.request("POST", url, headers=headers, data=payload)
XML模板内容
<?xml version="1.0" encoding="utf-8"?> <APIMethod xmlns="urn:Tool:apis:eBLBaseComponents"> <RequesterCredentials> <ToolAuthToken>%s</ToolAuthToken> </RequesterCredentials> <ItemID>12345678</ItemID> <MemberMessage> <Subject>Thanks</Subject> <Body>random text some information %s another information %s</Body> <QuestionType>General</QuestionType> <RecipientID>%s</RecipientID> </MemberMessage> </APIMethod>
内容的提问来源于stack exchange,提问作者Sven Sven
相关产品推荐
相关产品推荐

