是否在Python上使用zlib.compress,在Java(Android)上兼容Deflater.deflate?

Edu*_*ora 6 python java android zlib deflate

我正在将一个Python应用程序移植到Android,并且在某些时候,该应用程序必须与Web服务进行通信,并向其发送压缩数据.

为此,它使用下一个方法:

def stuff(self, data):
    "Convert into UTF-8 and compress."
    return zlib.compress(simplejson.dumps(data))
Run Code Online (Sandbox Code Playgroud)

我正在使用下一个方法尝试在Android中模拟此行为:

private String compressString(String stringToCompress)
{
    Log.i(TAG, "Compressing String " + stringToCompress);
    byte[] input = stringToCompress.getBytes(); 
    // Create the compressor with highest level of compression 
    Deflater compressor = new Deflater(); 
    //compressor.setLevel(Deflater.BEST_COMPRESSION); 
    // Give the compressor the data to compress 
    compressor.setInput(input); 
    compressor.finish(); 
    // Create an expandable byte array to hold the compressed data. 
    // You cannot use an array that's the same size as the orginal because 
    // there is no guarantee that the compressed data will be smaller than 
    // the uncompressed data. 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); 
    // Compress the data 
    byte[] buf = new byte[1024]; 
    while (!compressor.finished()) 
    { 
        int count = compressor.deflate(buf); 
        bos.write(buf, 0, count); 
    } 

    try { 
        bos.close(); 
    } catch (IOException e) 
    { 

    } 
    // Get the compressed data 
    byte[] compressedData = bos.toByteArray(); 

    Log.i(TAG, "Finished to compress string " + stringToCompress);

    return new String(compressedData);
}
Run Code Online (Sandbox Code Playgroud)

但是来自服务器的HTTP响应是不正确的,我想这是因为Java中的压缩结果与Python中的结果不同.

我用zlib.compress和deflate运行了一个小测试压缩"a".

Python,zlib.compress() - > x%9CSJT%02%00%01M%00%A6

Android,Deflater.deflate - > H%EF%BF%BDK%04%00%00b%00b

我应该如何在Android中压缩数据以在Python中获得相同的zlib.compress()值?

非常感谢任何帮助,指导或指针!

pat*_*yts 7

压缩和放气是不同的压缩算法,所以答案是它们不兼容.作为差异的一个例子,这里使用两个算法通过Tcl压缩'a':

% binary encode hex [zlib compress a]
789c4b040000620062
% binary encode hex [zlib deflate a]
4b0400
Run Code Online (Sandbox Code Playgroud)

你的python代码确实在做压缩.并且android代码正在进行deflate,但是你也获得了android版本前面的UTF-8字节顺序标记(\ xef\xbf\xbf)

您可以使用python发出deflate数据:

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
Run Code Online (Sandbox Code Playgroud)
>>> deflate("a")
'K\x04\x00'
Run Code Online (Sandbox Code Playgroud)


Edu*_*ora 2

尽管它们不是完全相同的算法,但它们似乎完全兼容(这意味着,例如,如果您使用 Deflater.deflate 压缩字符串,则可以使用 zlib 正确解压缩它)。

导致我的问题的原因是 POST 中的所有表单变量都需要进行百分比转义,而 Android 应用程序没有这样做。在发送数据之前将数据编码为 Base64,并修改服务器以在使用 zlib 解压缩之前使用 Base64 对其进行解码解决了该问题。