当前位置:   article > 正文

‘latin-1‘ codec can‘t encode characters in position 103-115: Body (‘一串中文‘) is not valid Latin-1_latin-1' codec can't encode characters in position

latin-1' codec can't encode characters in position 112-115: body ('完全报废
  • 1.问题:调用 requests.post 时,报错

    代码:

    str_params = json.dumps(tmp_params, ensure_ascii=False)
    headers = {"content-type": "application/json", "Connection": "close"}
    ret = requests.post(url=url, data=str_params, headers=headers)
    
    • 1
    • 2
    • 3

    错误提示:

    'latin-1' codec can't encode characters in position 103-115: Body ('一串中文xxx') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
    
    • 1
  • 2.挖掘问题
    根据错误提示:

    'latin-1' codec can't encode characters in position 103-115: Body ('一串中文xxx') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
    
    • 1

    可知,参数的编码是不对的,原因就是

    str_params = json.dumps(tmp_params, ensure_ascii=False)
    
    • 1

    这行代码,参数 ensure_ascii=False 会把非ascii转化为非utf-8编码(这里是明文形式的中文)。

  • 3.解决方法
    修改代码:

    str_params = json.dumps(tmp_params)
    headers = {"content-type": "application/json", "Connection": "close"}
    ret = requests.post(url=url, data=str_params, headers=headers)
    
    • 1
    • 2
    • 3

    再次运行程序即可正常执行。

    修改代码后,str_params 中的中文会编码成 \u9a6c\u94a2 形式, requests.post 默认接受utf-8的编码。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/378856
推荐阅读
相关标签
  

闽ICP备14008679号