Sto eseguendo il porting di un'applicazione Python su Android e, a un certo punto, questa applicazione deve comunicare con un servizio Web, inviandolo dati compressi.Are zlib.compress su Python e Deflater.deflate su Java (Android) compatibile?
Per farlo utilizza il metodo successivo:
def stuff(self, data):
"Convert into UTF-8 and compress."
return zlib.compress(simplejson.dumps(data))
Sto usando il metodo successivo per cercare di emulare questo comportamento in 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);
}
Ma la risposta HTTP dal il server non è corretto e immagino sia perché il risultato della compressione in Java non è uguale a quello in Python.
Ho eseguito un piccolo test comprimendo "a" entrambi con zlib.compress e deflate.
Python, zlib.compress() -> x% 9CSJT% 02% 00% 01M% 00% A6
Android, Deflater.deflate -> H% EF% BF% BDK% 04% 00% 00b % 00b
Come devo comprimere i dati in Android per ottenere lo stesso valore di zlib.compress() in Python?
Qualsiasi aiuto, guida o puntatore è molto apprezzato!
La riga 'return new String (compressedData);' è un bug. Non è possibile utilizzare String in questo modo. –