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

基本环境

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

解决方法

数据在网络中都是通过字节数据进行传输的, 在发送数据时, requests 模块需要将字符串编码成 bytes 进行传输.

而请求体 body 里面有汉字,requests里边的 URL 编码方式默认是 拉丁 编码,无法对中文内容进行编码

解决方式就是手动使用 utf-8 字符集对 data 进行编码.

// 得到中文
param_json = param and json.dumps(param, ensure_ascii=False)

with requests.Session() as session:
    resp = session.post(url, data=param_json.encode("utf-8"), timeout=HTTP_POST_TIMEOUT, headers=headers, **kwargs)

参考脚本之家:https://www.jb51.net/article/140386.htm

每天都要遇到更好的自己.
原文地址:https://www.cnblogs.com/kaichenkai/p/10931454.html