python - python Requests post数据为string类型时默认编码是什么?

标签 python python-requests

使用以下代码

payload = '''
 工作报告 
 总体情况:良好 
'''
r = requests.post("http://httpbin.org/post", data=payload)

Requests post数据为string类型时默认编码是什么? UTF8 还是 unicode-escape?

如果我想指定一种编码类型,我是否必须自己对其进行编码并将字节对象传递给参数“数据”?

最佳答案

根据最新的 JSON 规范 ( RFC-8259 ),当使用外部服务时,您必须将您的 JSON 负载编码为 UTF-8。这是一个快速解决方案:

r = requests.post("http://httpbin.org/post", data=payload.encode('utf-8'))

requests 使用 httplib 默认为 latin-1 编码。字节数组不会自动编码,因此最好使用它们。

我还建议使用 headers 参数设置字符集:

r = requests.post("http://httpbin.org/post", data=payload.encode('utf-8'),
                  headers={'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'})

关于python - python Requests post数据为string类型时默认编码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887958/

相关文章:

cas - Python 请求和 CAS

python - 决定在 Python 中捕获哪些异常

Python 中的 Java setRequestHeader

python - 使用 lxml 从父项中删除 xml 子项

python - 如何为包含整数的列表提取字符串?

python requests 模块 - 将键设置为 null

python - 无法从网站获取数据,因为获取数据时 URL 没有更改,因此数据表为空

python - 如何访问继承类的内部类并修改它?

python - 如何使用 Python 发出 URL 请求并返回重定向到的 URL?

python - 如何用文件作为键在 Python 中制作字典?