Are zlib.compress on Python and Deflater.deflate on Java (Android) compatible?

前端 未结 3 423
醉梦人生
醉梦人生 2020-12-20 18:49

I am porting a Python application to Android and, at some point, this application has to communicate with a Web Service, sending it compressed data.

In order to do t

3条回答
  •  [愿得一人]
    2020-12-20 19:21

    compress and deflate are different compression algorithms so the answer is they will not be compatible. As an example of the difference here is 'a' compressed using the two algorithms via Tcl:

    % binary encode hex [zlib compress a]
    789c4b040000620062
    % binary encode hex [zlib deflate a]
    4b0400

    Your python code is indeed doing compress. And the android code is doing deflate, however you are also getting the UTF-8 byte order mark prepended to the android version (\xef\xbf\xbf)

    You can emit deflate data using python:

    def deflate(data):
        zobj = zlib.compressobj(6,zlib.DEFLATED,-zlib.MAX_WBITS,zlib.DEF_MEM_LEVEL,0)
        zdata = zobj.compress(data)
        zdata += zobj.flush()
        return zdata
    
    >>> deflate("a")
    'K\x04\x00'

提交回复
热议问题