zoukankan      html  css  js  c++  java
  • requests Use body.encode('utf-8') if you want to send it encoded in UTF-8

    基本环境

    使用 requests 模块发送 post 请求,请求体包含中文报错

    系统环境:centos7.3

    python版本:python3.6.8

    请求代码:

    // 得到中文
    param_json = param and json.dumps(param, ensure_ascii=False)
    
    with requests.Session() as session:
        resp = session.post(url, data=param_json, timeout=HTTP_POST_TIMEOUT, headers=headers, **kwargs)

    汉字报错,报错详细内容: 'latin-1' codec can't encode characters in position 545-547: Body ('未识别') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8

    解决方法

    数据在网络中都是通过字节数据进行传输的, 在发送数据时, requests 模块需要将字符串编码成 bytes 进行传输.

    而请求体 body 里面有汉字,requests里边的 URL 编码方式默认是 拉丁 编码,无法对中文内容进行编码

    解决方式就是手动使用 utf-8 字符集对 data 进行编码.

    // 得到中文
    param_json = param and json.dumps(param, ensure_ascii=False)
    
    with requests.Session() as session:
        resp = session.post(url, data=param_json.encode("utf-8"), timeout=HTTP_POST_TIMEOUT, headers=headers, **kwargs)
    

    参考脚本之家:https://www.jb51.net/article/140386.htm

    每天都要遇到更好的自己.
  • 相关阅读:
    js作用域
    正则表达式方法
    for-in
    关于this
    由indexOf引发的一系列探究和思考
    Html第一个程序
    转:1.ASP.Net MVC开发基础学习笔记;2.HtmlHelper与扩展方法
    转:单例模式
    转:ORM框架EF(Entity framework)实体框架
    C#lambda表达式
  • 原文地址:https://www.cnblogs.com/kaichenkai/p/10931454.html
Copyright © 2011-2022 走看看