使用httplib的POST二进制数据会导致Unicode异常

当我尝试使用urllib2发送图像时,发生UnicodeDecodeError异常。


HTTP Post正文:


f = open(imagepath, "rb")

binary = f.read()

mimetype, devnull = mimetypes.guess_type(urllib.pathname2url(imagepath))


body = """Content-Length: {size}

Content-Type: {mimetype}


{binary}

""".format(size=os.path.getsize(imagepath),  

           mimetype=mimetype,

           binary=binary)


request = urllib2.Request(url, body, headers)

opener = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel=1))

response = opener.open(request)

print response.read()

追溯 :


   response = opener.open(request)

  File "/usr/local/lib/python2.7/urllib2.py", line 404, in open

    response = self._open(req, data)

  File "/usr/local/lib/python2.7/urllib2.py", line 422, in _open

    '_open', req)

  File "/usr/local/lib/python2.7/urllib2.py", line 382, in _call_chain

    result = func(*args)

  File "/usr/local/lib/python2.7/urllib2.py", line 1222, in https_open

    return self.do_open(httplib.HTTPSConnection, req)

  File "/usr/local/lib/python2.7/urllib2.py", line 1181, in do_open

    h.request(req.get_method(), req.get_selector(), req.data, headers)

  File "/usr/local/lib/python2.7/httplib.py", line 973, in request

    self._send_request(method, url, body, headers)

  File "/usr/local/lib/python2.7/httplib.py", line 1007, in _send_request

    self.endheaders(body)

  File "/usr/local/lib/python2.7/httplib.py", line 969, in endheaders

    self._send_output(message_body)

  File "/usr/local/lib/python2.7/httplib.py", line 827, in _send_output

    msg += message_body

  File "/home/usertmp/biogeek/lib/python2.7/encodings/utf_8.py", line 16, in decode

    return codecs.utf_8_decode(input, errors, True)

UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 49: invalid start byte

python版本2.7.5


有人知道解决方案吗?


湖上湖
浏览 300回答 1
1回答

长风秋雁

您正在尝试发送包含标题和内容的正文。如果要发送内容类型和内容长度,则需要在标题中而不是在正文中进行:headers = {'Content-Type': mimetype, 'Content-Length', str(size)}request = urllib2.Request(url, data=binary, headers=headers)如果您未设置Content-Length标头,则会自动将其设置为 data关于您的错误:它正在发生msg += message_body仅当这两个字符串之一为unicode,而另一个str包含时\xff,才可能发生此错误,因为在这种情况下,后者会使用来自动转换为unicode sys.getdefaultencoding()。我的最终猜测是:message_body这是您的data,它是一个str,包含在\xff某处。msg是什么东西已经传递到前面的HttpConnection,即头,他们都是unicode的,因为你要么采用的是Unicode在你的头部至少一个键(值转换为str更早),或已导入unicode_literals的__futures__。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python