当用request发送的xml文件标签数据包含中文时,可能会报错。
报错提示:UnicodeEncodeError: 'latin-1' codec can't encode characters in position 174-176: Body ('方晶晶') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
那么这时候,需要对数据部分进行utf-8编码,方法如下
rqs_headers = {"Content-Type": "text/xml; charset=utf-8"}
url = "http://xxxx"
response = requests.post(url, data=doc.toxml(encoding='utf-8'), headers=rqs_headers)
另外也可以尝试如下链接中方法,未测试过。

当使用requests库发送包含中文的XML文件时,可能会遇到Unicode编码错误。为解决此问题,需要设置请求头的`Content-Type`为`text/xml;charset=utf-8`,并确保XML数据使用`utf-8`编码。例如:`response=requests.post(url,data=doc.toxml(encoding='utf-8'),headers=rqs_headers)`。此外,文中还提供了可能的解决方案链接供参考。

2万+

被折叠的 条评论
为什么被折叠?



