使用 http.client lib (Python) 的 GET 请求中的字符编码

Dev*_*Dev 3 python get utf-8 httprequest python-3.3

我是 python 的初学者,我编写了这个小脚本来在本地服务器 (localhost) 上发送 HTTP GET 请求。它工作得很好,除了我希望我可以发送拉丁字符,例如重音符号。

import http.client

httpMethod = "GET"
url = "localhost"
params = "Hello World"

def httpRequest(httpMethod, url, params):
    conn = http.client.HTTPConnection(url)
    conn.request(httpMethod, '/?param='+params)
    conn.getresponse().read()
    conn.close()
    return

httpRequest(httpMethod, url, params)
Run Code Online (Sandbox Code Playgroud)

当我在参数“params”中插入带重音的单词时,出现以下错误消息:

UnicodeEncodeError:“ascii”编解码器无法对位置 14 中的字符“\xe9”进行编码:序数不在范围内(128)

我不知道是否有使用 http.client 库的解决方案,但我认为是的。当我查看文档 http.client 时,我可以看到:

HTTPConnection.request

字符串编码为 ISO-8859-1,HTTP 的默认字符集

kir*_*gin 5

您不应该手动构造参数。改用urlencode

\n\n
>>> from urllib.parse import urlencode\n>>> params = \'Aserej\xc3\xa9\'\n>>> urlencode({\'params\': params})\n\'params=Aserej%C3%A9\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以,你可以这样做:

\n\n
conn.request(httpMethod, \'/?\' + urlencode({\'params\': params}))\n
Run Code Online (Sandbox Code Playgroud)\n\n

另请注意,yout 字符串在进行 URL 转义之前将被编码为 UTF-8

\n