Skip to main content
 首页 » 编程设计

python之使用 httplib POST 二进制数据导致 Unicode 异常

2024年11月01日10unruledboy

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

HTTP 帖子正文:

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

有人知道解决这个问题的方法吗?

请您参考如下方法:

您正在尝试发送包含 header 和内容的正文。如果要发送内容类型和内容长度,则需要在标题中而不是正文中进行:

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 时,才会发生此错误,如下所示如果后者将使用 sys.getdefaultencoding() 自动转换为 unicode。

我的最终猜测是:message_body 这是您的 data,它是一个 str 并包含 \xff 某个地方。 msg 是之前传递给 HTTPConnection 的内容,即 header ,它们是 unicode,因为您要么将 unicode 用于 header 中的至少一个键(值被转换为 str 之前),或者您已经从 __futures__ 导入了 unicode_literals。