最近写程序发现关于requests上传中文参数时候编码有问题,而把代码换成Python2确没有问题,十分困扰,具体的问题是
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\api.py", line 112, in post
return request('post', url, data=data, json=json, **kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\adapters.py", line 445, in send
timeout=timeout
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen
chunked=chunked)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\connectionpool.py", line 357, in _make_request
conn.request(method, url, **httplib_request_kw)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 1284, in _send_request
body = _encode(body, 'body')
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\http\client.py", line 161, in _encode
(name.title(), data[err.start:err.end], name)) from None
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 21258-21262: Body ('测试不正常') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
ok,那我编码成utf-8
试试,出现以下错误:
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'bytes' is not JSON serializable
bytes格式的还不行,仔细思考了一下错误,最终将代码改成了
userInfo = name.encode("utf-8").decode("latin1")
先编码成bytes格式再解码为latin1