UnicodeEncodeError:'ascii'编解码器在Python中尝试HTTP POST时无法对字符进行编码

Dav*_*vid 10 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)
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题的任何想法?

msa*_*ers 13

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

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