request模块做post请求时,body为json格式,并且带有中文,如何请求

ruancan 2017-05-23 08:45:15
# encoding=utf-8
import requests

url = 'http://httpbin.org/post'
d = {'key1': 'value1', 'key2': '你好'}
r = requests.post(url, json=d)
print r.text

这样写的话,请求的body变成了{"key2": "\u4f60\u597d", "key1": "value1"}

# encoding=utf-8
import json

import requests

url = 'http://httpbin.org/post'
d = {'key1': 'value1', 'key2': u'你好'}
r = requests.post(url, data=json.dumps(d, ensure_ascii=False))
print r.text
这样写的话报错:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-11: ordinal not in range(128)

如何才能使请求的body为:{"key2": "你好", "key1": "value1"}
后台接口只能解析json,并且一定要是中文才能解析出来,如果是unicode编码的中文则会报错

...全文
5501 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
颖辉小居 2020-08-06
  • 打赏
  • 举报
回复
试了不行,paython 3.8 moco 1.1
qq_34390294 2021-07-02
  • 举报
回复
@颖辉小居 请问解决了吗 我也遇到了这个问题
ruancan 2017-05-23
  • 打赏
  • 举报
回复
好了,问题已经解决了,看了一下requests的源码.以下为解决方法: 将requests库中的models.py文件中的第461行: body = complexjson.dumps(json) 修改为: body = complexjson.dumps(json, separators=(',', ':'), ensure_ascii=False) 使用: # encoding=utf-8 import requests url = 'http://httpbin.org/post' d = {'key1': 'value1', 'key2': '你好'} r = requests.post(url, json=d) print r.text 即可使得body中的json串直接为中文 fiddler中的抓包信息如下: POST http://httpbin.org/post HTTP/1.1 Host: httpbin.org Connection: keep-alive Accept-Encoding: gzip, deflate Accept: */* User-Agent: python-requests/2.13.0 Content-Length: 33 Content-Type: application/json {"key2":"你好","key1":"value1"}

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧