欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GZIP压缩解压类

程序员文章站 2024-03-14 09:17:54
...

    针对一些与APP交互的网站,经常用json格式,这样明文有些不安全以及很容易被爬,且数据量大,因此用gzip来进行压缩并用base64编码,避免上述问题,直接上代码:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP压缩解压类
 */
public class StringGZIP {

	private static String encode = "UTF-8";

	private static final String CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-/=";

	/**
	 * base64解密
	 * 
	 * @param input
	 * @return
	 */
	public static byte[] base64Decode(String input) {
		if (input.length() % 4 != 0) {
			throw new IllegalArgumentException("Invalid base64 input");
		}
		byte decoded[] = new byte[((input.length() * 3) / 4)
				- (input.indexOf('=') > 0 ? (input.length() - input.indexOf('=')) : 0)];
		char[] inChars = input.toCharArray();
		int j = 0;
		int b[] = new int[4];
		for (int i = 0; i < inChars.length; i += 4) {
			// This could be made faster (but more complicated) by precomputing
			// these index locations.
			b[0] = CODES.indexOf(inChars[i]);
			b[1] = CODES.indexOf(inChars[i + 1]);
			b[2] = CODES.indexOf(inChars[i + 2]);
			b[3] = CODES.indexOf(inChars[i + 3]);
			decoded[j++] = (byte) ((b[0] << 2) | (b[1] >> 4));
			if (b[2] < 64) {
				decoded[j++] = (byte) ((b[1] << 4) | (b[2] >> 2));
				if (b[3] < 64) {
					decoded[j++] = (byte) ((b[2] << 6) | b[3]);
				}
			}
		}
		return decoded;
	}

	/**
	 * base64加密
	 * 
	 * @param in
	 * @return
	 */
	public static String base64Encode(byte[] in) {
		StringBuilder out = new StringBuilder((in.length * 4) / 3);
		int b;
		for (int i = 0; i < in.length; i += 3) {
			b = (in[i] & 0xFC) >> 2;
			out.append(CODES.charAt(b));
			b = (in[i] & 0x03) << 4;
			if (i + 1 < in.length) {
				b |= (in[i + 1] & 0xF0) >> 4;
				out.append(CODES.charAt(b));
				b = (in[i + 1] & 0x0F) << 2;
				if (i + 2 < in.length) {
					b |= (in[i + 2] & 0xC0) >> 6;
					out.append(CODES.charAt(b));
					b = in[i + 2] & 0x3F;
					out.append(CODES.charAt(b));
				} else {
					out.append(CODES.charAt(b));
					out.append('=');
				}
			} else {
				out.append(CODES.charAt(b));
				out.append("==");
			}
		}
		return out.toString();
	}

	public String getEncode() {
		return encode;
	}

	/*
	 * 设置 编码,默认编码:UTF-8
	 */
	public void setEncode(String encode) {
		StringGZIP.encode = encode;
	}

	/**
	 * 字符串压缩为字节数组,默认UTF-8编码
	 * 
	 * @param str
	 * @return
	 */
	public static String compress(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes(encode));
			gzip.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return base64Encode(out.toByteArray());
	}

	/**
	 * 字符串压缩为字节数组
	 * 
	 * @param str
	 * @param encoding
	 * @return
	 */
	public static String compress(String str, String encoding) {
		if (str == null || str.length() == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes(encoding));
			gzip.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return base64Encode(out.toByteArray());
	}

	/**
	 * 字节数组解压缩后返回字符串,默认编码为UTF-8
	 * 
	 * @param zipText
	 * @return
	 */
	public static String decompress(String zipText) {
		byte[] b = base64Decode(zipText);
		if (b == null || b.length == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(b);

		try {
			GZIPInputStream gunzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toString();
	}

	/**
	 * 字节数组解压缩后返回字符串
	 * 
	 * @param zipText
	 * @param encoding
	 * @return
	 */
	public static String decompress(String zipText, String encoding) {
		byte[] b = base64Decode(zipText);
		if (b == null || b.length == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(b);

		try {
			GZIPInputStream gunzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
			return out.toString(encoding);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

    使用案例:

    @Test
    public void decompress1() {
        String tempString = "sdfji汉字测试";
        String compress = StringGZIP.compress(tempString);
        System.out.println(compress);
        String decompress = StringGZIP.decompress(compress);
        System.out.println(decompress);
        tempString = "sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试";
         compress = StringGZIP.compress(tempString);
        System.out.println(compress);
         decompress = StringGZIP.decompress(compress);
        System.out.println(decompress);
    }

    测试输出:

H4sIAAAAAAAAACtOScvKfLax8+na6c+2dr9YPxUAoOKrwBEAAAA=
sdfji汉字测试
H4sIAAAAAAAAACtOScvKfLax8+na6c+2dr9YP7V4sAoAAO-IIA6qAAAA
sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试sdfji汉字测试

 

    对于重复字段越多,压缩率越高!

转载于:https://my.oschina.net/xldc/blog/711202