【发布时间】:2011-01-26 08:47:07
【问题描述】:
我正在将一个 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()相同的值?
非常感谢任何帮助、指导或指针!
【问题讨论】:
-
return new String(compressedData);行是一个错误。你不能那样使用字符串。
标签: java python android zlib deflate