客戶端需要上傳一些信息到服務器,數據重複性比較高。所以想到zip壓縮。
php端
$jsonString = gzcompress($jsonString);//壓縮
$json=gzuncompress($jsonString);//解壓
android端
public static byte[] getGZipCompressed(String data) {
byte[] compressed = null;
try {
byte[] byteData = data.getBytes();
ByteArrayOutputStream bos = new ByteArrayOutputStream(
byteData.length);
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION); // 將當前壓縮級別設置爲指定值。
compressor.setInput(byteData, 0, byteData.length);
compressor.finish(); // 調用時,指示壓縮應當以輸入緩衝區的當前內容結尾。
// Compress the data
final byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
compressor.end(); // 關閉解壓縮器並放棄所有未處理的輸入。
compressed = bos.toByteArray();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return compressed;
}
public static byte[] getGZipUncompress(byte[] data) throws IOException {
byte[] unCompressed = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
Inflater decompressor = new Inflater();
try {
decompressor.setInput(data);
final byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
unCompressed = bos.toByteArray();
bos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
decompressor.end();
}
// String test = bos.toString();
return unCompressed;
}