分享一段gzip解压的代码

对接接口时,有的接口采用了gzip压缩,需要解压,具体的方法可采用:
compressData--代表接口获取到的压缩的资源,则具体的思路为:

byte[] bytes = decoder.decodeBuffer(compressData); 
ByteArrayOutputStream byteArray = uncompress(bytes);
String json = byteArray.toString("UTF-8");

/**
*gzip解压代码
**/
public static ByteArrayOutputStream uncompress(byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = new ByteArrayInputStream(bytes);
    try {
        GZIPInputStream ungzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = ungzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
     } catch (IOException e) {

       }
    return out;
}

以上代码在应用时,需因代码而异,可能需要做出一些更改。。

你可能感兴趣的:(java)