我正在将一个Python应用程序移植到Android上,并且在某种程度上,此应用程序必须与Web服务进行通信,并向其发送压缩数据。zlib.compress是否与Java兼容的Java(Android)上的Python和Deflater.deflate?
为了做到这一点,它使用下一个方法:
def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.dumps(data))
我用下一个方法来试图模仿这种行为在安卓
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中的压缩结果不一样。
我跑了一个测试压缩“a”与zlib.compress和deflate。
的Python,zlib.compress() - > X%9CSJT%02%00%01M%00%A6
机器人,Deflater.deflate - > H%EF%BF%BDK%04%00%00B %00b
我应该如何压缩Android中的数据才能获得与Python中zlib.compress()相同的值?
任何帮助,指导或指针非常感谢!
行'return new String(compressedData);'是一个错误。你不能以这种方式使用String。 – 2011-04-03 21:22:31