Implementation of gzip in java

Implementation of gzip in java

server.java


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @GetMapping
    public void test(HttpServletRequest request, HttpServletResponse reponse) throws IOException {
        
        //响 application body
        String content = "A long time ago, there was a shortage of hoto, and this morning I was sick. Spring horseshoe, horseshoe, and Chang'an, who has been watching for a day.";
        
        String acceptEncooding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);
        
        /**
         *获 获 舷 舷 舷 職 Supporting editing system, the degree can root setting this individual header judgment approval or disapproval required
         */
        LOGGER.info(acceptEncooding);
        
        
        //响 application body use gzip editing
        reponse.setHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
        //Typological type string
        reponse.setContentType(MediaType.TEXT_PLAIN_VALUE);
        //Encoding utf-8
        reponse.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        //Gzip compression
        reponse.getOutputStream().write(gZip(content.getBytes(StandardCharsets.UTF_8)));
        
    }

    /**
     *Gzip compression data
     * @param data
     * @return
     * @throws IOException
     */
    public static byte[] gZip(byte[] data) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
            gzipOutputStream.write(data);
            gzipOutputStream.finish();
            return byteArrayOutputStream.toByteArray();
        }
    }
}

client.java


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class Main {

    public static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws Exception {
        
        RestTemplate restTemplate = new RestTemplate();
        
        
        HttpHeaders httpHeaders = new HttpHeaders();
        //Accept Display Client Support 什么 Formal 响 application
        httpHeaders.set(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE);
        // Accept-Encoding 头, display client end requisition gzip formal compression
        httpHeaders.set(HttpHeaders.ACCEPT_ENCODING, "gzip");
        
        ResponseEntity<byte[]> responseEntity = restTemplate.exchange("http://localhost/test", HttpMethod.GET, new HttpEntity<>(httpHeaders), byte[].class);
        
        if (!responseEntity.getStatusCode().is2xxSuccessful()) {
            //TODO non-200 响 application
        }

        //获tori service equipment 响 application body edition
        String contentEncoding = responseEntity.getHeaders().getFirst(HttpHeaders.CONTENT_ENCODING);
        
        if ("gzip".equals(contentEncoding)) { //gzip editing
            //gzip server
            byte[] data = unGZip(new ByteArrayInputStream(responseEntity.getBody()));
            
            LOGGER.info(new String(data, StandardCharsets.UTF_8));
        } else {
            //TODO Other editing
        }
    }

    /**
     *Gzip compression
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] unGZip(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) {
            byte[] buf = new byte[4096];
            int len = -1;
            while ((len = gzipInputStream.read(buf, 0, buf.length)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            return byteArrayOutputStream.toByteArray();
        } finally {
            byteArrayOutputStream.close();
        }
    }
}

that's all!

Recommended Posts

Implementation of gzip in java
Implementation of tri-tree in Java
Implementation of like function in Java
Interpreter implementation in Java
Implementation of DBlayer in Java (RDB, MySQL)
Boyer-Moore implementation in Java
Heapsort implementation (in java)
[Java] Implementation of Faistel Network
Implementation of HashMap in kotlin
Implementation of ls command in Ruby
Implementation of asynchronous processing in Tomcat
List of members added in Java 9
List of types added in Java 9
Implementation of clone method for Java Record
[Java] I participated in ABC-188 of Atcorder.
Get the result of POST in Java
Let's create a TODO application in Java 4 Implementation of posting function
Partization in Java
Implementation of multi-tenant asynchronous processing in Tomcat
Let's create a TODO application in Java 6 Implementation of search function
Changes in Java 11
Let's create a TODO application in Java 8 Implementation of editing function
Rock-paper-scissors in Java
Mechanism and characteristics of Collection implementation class often used in Java
Implementation of GKAccessPoint
The story of writing Java in Emacs
Pi in Java
[Java] Overview of Java
Role of JSP in Web application [Java]
FizzBuzz in Java
Reading and writing gzip files in Java
Discrimination of Enums in Java 7 and above
This and that of the implementation of date judgment within the period in Java
Comparison of thread implementation methods in Java and lambda expression description method
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
Do you need a memory-aware implementation of Java?
Implementation of digit grouping in flea market apps
The story of learning Java in the first programming
Measure the size of a folder in Java
SKStoreReviewController implementation memo in Swift UI of iOS14
[Java] Use of final in local variable declaration
Feel the passage of time even in Java
[Rails] Implementation of retweet function in SNS application
[JQuery] Implementation procedure of AutoComplete function [Java / Spring]
[Java / Spring Boot] Spring security ④ --Implementation of login process
[Rails] Implementation of "notify notification in some way"
[Java / Spring Boot] Spring security ⑤ --Implementation of logout processing
A quick review of Java learned in class
Method name of method chain in Java Builder + α
Import files of the same hierarchy in Java
Why use setters/getters instead of public/private in Java
[java] sort in list
Expired collection of java
Read JSON in Java
Predicted Features of Java
Rock-paper-scissors app in Java
Constraint programming in Java
[Java] Significance of serialVersionUID
Implementation of flash messages