When i try to send an image with urllib2 the UnicodeDecodeError exception is occured.
HTTP Post body:
f = op
You're trying to send a body containing headers and content. If you want to send content type and content length, you need to do it in the headers, not in the body:
headers = {'Content-Type': mimetype, 'Content-Length', str(size)}
request = urllib2.Request(url, data=binary, headers=headers)
If you don't set the Content-Length header, it will be automatically set to the size of data
As to your error: it's happening on the line
msg += message_body
This error can only happen, if one of these two strings is unicode
, and the other str
containing \xff
, as in that case the latter will be automatically coecred to unicode using sys.getdefaultencoding()
.
My final guess would be: message_body
here is your data
, which is a str
and contains \xff
somewhere. msg
is what has been passed to the HTTPConnection earlier, namely the headers, and they are unicode because you either used unicode for at least one key in your headers (the values are converted to str
earlier), or you have imported unicode_literals
from __futures__
.