赞
踩
1.问题:调用 requests.post 时,报错
代码:
str_params = json.dumps(tmp_params, ensure_ascii=False)
headers = {"content-type": "application/json", "Connection": "close"}
ret = requests.post(url=url, data=str_params, headers=headers)
错误提示:
'latin-1' codec can't encode characters in position 103-115: Body ('一串中文xxx') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
2.挖掘问题
根据错误提示:
'latin-1' codec can't encode characters in position 103-115: Body ('一串中文xxx') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
可知,参数的编码是不对的,原因就是
str_params = json.dumps(tmp_params, ensure_ascii=False)
这行代码,参数 ensure_ascii=False 会把非ascii转化为非utf-8编码(这里是明文形式的中文)。
3.解决方法
修改代码:
str_params = json.dumps(tmp_params)
headers = {"content-type": "application/json", "Connection": "close"}
ret = requests.post(url=url, data=str_params, headers=headers)
再次运行程序即可正常执行。
修改代码后,str_params 中的中文会编码成 \u9a6c\u94a2 形式, requests.post 默认接受utf-8的编码。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。