2018-06-13 RestTemplate处理Gzip压缩

2018-06-19 15:42:00 浏览数 (2)

遇到了一个RestTemplate请求带Gzip压缩的时候不会自动解压的问题

网络上很多都是让用httpClient来解决这个问题

后来找到这个文章

https://stackoverflow.com/questions/34415144/how-to-parse-gzip-encoded-response-with-resttemplate-from-spring-web

但发现CompressionUtil.decompressGzipByteArray 这个方法,没找到jar包

最后找到了这个方法

代码语言:javascript复制
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-jcs -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-jcs</artifactId>
            <version>2.2</version>
            <type>pom</type>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
代码语言:javascript复制
    public static String decompress(final byte[] compressed) {
        if (isNull(compressed) || compressed.length == 0) {
            return null;
        }

        try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
             final StringWriter stringWriter = new StringWriter()) {
            IOUtils.copy(gzipInput, stringWriter, UTF_8);
            return stringWriter.toString();
        } catch (IOException e) {
            throw new UncheckedIOException("Error while decompression!", e);
        }
    }

解压一下就可以用了

0 人点赞