android php互相壓縮解壓

客戶端需要上傳一些信息到服務器,數據重複性比較高。所以想到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;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章