How to zip- compress HTTP request with Spring RestTemplate?

后端 未结 3 1166
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 04:53

How to gzip HTTP request, created by org.springframework.web.client.RestTemplate?

I am using Spring 4.2.6 with Spring

3条回答
  •  感情败类
    2020-12-31 05:37

    Further to the above answer from @TestoTestini, if we take advantage of Java 7+'s 'try-with-resources' syntax (since both ByteArrayOutputStream and GZIPOutputStream implement closeable() ) then we can shrink the getGzip function into the following:

    private byte[] getGzip(byte[] body) throws IOException {
    
        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
             GZIPOutputStream zipStream = new GZIPOutputStream(byteStream)) {
                zipStream.write(body);
            byte[] compressedData = byteStream.toByteArray();
            return compressedData;
        }
    
    }
    

    (I couldn't find a way of commenting on @TestoTestini's original answer and retaining the above code format, hence this Answer).

提交回复
热议问题