Python上的zlib.compress和Java(Android)上的Deflater.deflate是否兼容?
我正在将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()值?
任何帮助,指导或指针,我们将不胜感激!