python - 统一码编码错误 : 'ascii' codec can't encode character when trying a HTTP POST in Python

标签 python unicode ascii http-post

我正在尝试使用 Unicode 字符串 (u'\xe4\xf6\xfc') 作为 Python 中的参数执行 HTTP POST,但我收到以下错误:

UnicodeEncodeError: 'ascii' 编解码器无法编码字符

这是用于制作 HTTP POST 的代码(使用 httplib2)

 http = httplib2.Http()  
 userInfo = [('Name', u'\xe4\xf6\xfc')]
 data = urlencode(userInfo)

 resp, content = http.request(url, 'POST', body=data)

关于如何解决这个问题有什么想法吗?

最佳答案

您不能直接 POST Python Unicode 对象。您应该首先将其编码为 UTF-8 字符串:

name = u'\xe4\xf6\xfc'.encode('utf-8')
userInfo = [('Name', name)]

关于python - 统一码编码错误 : 'ascii' codec can't encode character when trying a HTTP POST in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3110104/

相关文章:

go - 如何像 python 一样在 go 中打印 ascii 文本

python - 根据python中的自定义函数聚合数据框中的每一列

python - 在连通分量标记函数后计算图像矩

python - 如何制作 5.1 和 7.1 环绕声文件

python - 想要连接随机均匀生成的值

c++ - 使用 libharu 在 pdf 中打印日文字符

java - 为什么 "\400"不是编译时错误?

Java - 将字母字符串转换为相应 ascii 的整数?

python - 如何标准化 Python 字符串编码

python - Django python manage.py 收集静态 UnicodeDecodeError : 'ascii' codec can't decode byte 0xcc in position 32: ordinal not in range(128)