使用 requests 模块发送 post 请求,请求体包含中文报错
系统环境:centos7.3
python版本:python3.6.8
请求代码:
// 得到中文 param_json = param and json.dumps(param, ensure_ascii=False) with requests.Session() as session: resp = session.post(url, data=param_json, timeout=HTTP_POST_TIMEOUT, headers=headers, **kwargs)
汉字报错,报错详细内容: ‘latin-1‘ codec can‘t encode characters in position 545-547: Body (‘未识别‘) is not valid Latin-1. Use body.encode(‘utf-8‘) if you want to send it encoded in UTF-8
是因为请求体 body 里面有汉字,不能被 URL 编码处理,解决方式就是对 data 进行 encode() 编码,使得参数原样输出,不需要编码处理:
// 得到中文
param_json = param and json.dumps(param, ensure_ascii=False)
with requests.Session() as session:
resp = session.post(url, data=param_json.encode(), timeout=HTTP_POST_TIMEOUT, headers=headers, **kwargs)
参考脚本之家:https://www.jb51.net/article/140386.htm
requests Use body.encode('utf-8') if you want to send it encoded in UTF-8
原文:https://www.cnblogs.com/kaichenkai/p/10931454.html