我正在將一個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