夜阑卧听风吹雨

铁马冰河入梦来

Loading

requests httpx post中json中文编码问题

背景

requests、httpx post 提交 json 数据时,默认在库中 ensure_asciiTrue。会对中文进行 unicode 编码。

但是有的时候服务端并没有处理中文,没有进行解码,而我们又改不了服务端,就会出现问题!

解决

  1. 修改库的代码,添加上对应的 ensure_ascii 参数。不推荐,换个环境就用不了了。

  2. 推荐,自己提交 json,自己提交二进制数据,不让库来编码我们的数据。

    因为不是用 json 关键字参数,不会自动在请求头中添加 Content-Type,所以我们必须手动在请求头中添加 "Content-Type": "application/json"。大致代码如下:

# request
import json
import requests

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post('https://httpbin.org/post', data=json.dumps({'id': 1, 'name': '杰克'}, ensure_ascii=False).encode("utf-8"), headers=headers)
print(response.text)

# httpx
import httpx

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = httpx.post('https://httpbin.org/post', content=json.dumps({'id': 1, 'name': '杰克'}, ensure_ascii=False).encode("utf-8"),
                      headers=headers)
print(response.text)

httpbin 的响应中,中文好像自动编码了,实际上提交到服务器的数据就没有对中文进行编码了。

posted @ 2023-02-14 15:59  二次蓝  阅读(233)  评论(0编辑  收藏  举报