美文网首页
aiohttp post的数据为特定编码的坑

aiohttp post的数据为特定编码的坑

作者: 小云柳 | 来源:发表于2020-03-10 23:13 被阅读0次

今天遇到一个问题,我需要post的表单数据有中文,抓包之后看到提交的表单里中文部分是不显示中文的,而是显示(unable to decode value),然后看了网站的编码为gb2312。在这里假设我的表单是这样子的

data = {"type": "0", "name": "小张", "btnGetRealty": "查询"}

当我用requests这个http客户端进行请求时:

data = {"type": "0", "name": "小张".encode("gb2312"), "btnGetRealty": "查询".encode("gb2312")}
resp = requests.post(url, data=data)

通过requests请求时可以返回正确的数据的。

然而当我用aiohttp这个异步客户端请求时如下:

data = {"type": "0", "name": "小张".encode("gb2312"), "btnGetRealty": "查询".encode("gb2312")}
async with aiohttp.ClientSession() as session:
    html = await session.post(url, data=data, verify_ssl=False)
    print(html)

不管我怎么请求都没有返回正确结果,猜想应该是post表单不正确,经过查找,找到了解决方案:

data = {"type": "0", "name": "小张", "btnGetRealty": "查询"}
form_data = aiohttp.FormData(data, charset="gb2312")
async with aiohttp.ClientSession() as session:
   html = await session.post(url, data=form_data, verify_ssl=False)
   print(html)

这样结果终于正确了。

记录一下这个小坑,方便以后查询.

相关文章

网友评论

      本文标题:aiohttp post的数据为特定编码的坑

      本文链接:https://www.haomeiwen.com/subject/lcqodhtx.html