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

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

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

我正在使用下一种方法来尝试在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);
}

但是来自服务器的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()值?

任何帮助,指导或指针,我们将不胜感激!

最佳答案

compress和deflate是不同的压缩算法,因此答案是它们将不兼容。作为区别的一个示例,这里是通过Tcl使用两种算法压缩的“a”:

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

您的python代码确实在执行压缩。并且android代码正在执行deflate,但是您也会在android版本(\xef\xbf\xbf)之前添加UTF-8字节顺序标记

您可以使用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
>>> deflate("a")
'K\x04\x00'

10-05 21:13
查看更多