Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnicodeEncodeError: 'ascii' codec can't encode character when trying a HTTP POST in Python

I'm trying to do a HTTP POST with a unicode string (u'\xe4\xf6\xfc') as a parameter in Python, but I receive the following error:

UnicodeEncodeError: 'ascii' codec can't encode character

This is to the code used to make the HTTP POST (with httplib2)

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

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

Any ideas on how to solve this?

like image 721
David Avatar asked Jun 24 '10 12:06

David


1 Answers

You cannot POST Python Unicode objects directly. You should encode it as a UTF-8 string first:

name = u'\xe4\xf6\xfc'.encode('utf-8')
userInfo = [('Name', name)]
like image 124
msanders Avatar answered Sep 28 '22 03:09

msanders