requests Use body.encode('utf-8') if you want to send it encoded in UTF-8

时间:2019-05-27 17:21:28   收藏:0   阅读:989

基本环境

使用 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

 

原文:https://www.cnblogs.com/kaichenkai/p/10931454.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!