我是 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)
当我在参数“params”中插入带重音的单词时,出现的错误消息如下:
UnicodeEncodeError:“ascii”编解码器无法对位置 14 中的字符“\xe9”进行编码:序号不在范围内 (128)
我不知道是否有使用 http.client 库的解决方案,但我认为是的。当我查看文档 http.client 时,我可以看到:
HTTPConnection.request
字符串编码为 ISO-8859-1,HTTP 的默认字符集
最佳答案
您不应该手动构造参数。使用 urlencode
相反:
>>> from urllib.parse import urlencode
>>> params = 'Aserejé'
>>> urlencode({'params': params})
'params=Aserej%C3%A9'
所以,你可以这样做:
conn.request(httpMethod, '/?' + urlencode({'params': params}))
另请注意,您的字符串在进行 URL 转义之前将被编码为 UTF-8。
关于python - 使用 http.client lib (Python) 的 GET 请求中的字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985810/