10

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?

msanders
  • 5,739
  • 1
  • 29
  • 30
David
  • 133
  • 1
  • 1
  • 8

1 Answers1

13

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)]
msanders
  • 5,739
  • 1
  • 29
  • 30
  • Had some problem with the encoding earlier, but then i did it inline. Like this: userInfo = [('Name', u'\xe4\xf6\xfc'.encode('utf-8'))] Anyway thanks for a quick response – David Jun 24 '10 at 13:25
  • Its very similar question of this post, http://stackoverflow.com/questions/1652904/easy-q-unicodeencodeerror-ascii-codec-cant-encode-character – shahjapan Jun 26 '10 at 16:33
  • 1
    It would be helpful if the documentation for httplib2 and httplib mentioned this constraint. – chernevik Dec 16 '11 at 18:15