HTTP request compression

前端 未结 3 662
傲寒
傲寒 2020-12-02 00:44

General Use-Case

Imagine a client that is uploading large amounts of JSON. The Content-Type should remain application/json because that

3条回答
  •  天命终不由人
    2020-12-02 01:27

    Add to your header when you are sending:

    JSON : "Accept-Encoding" : "gzip, deflate"
    

    Client code :

    HttpUriRequest request = new HttpGet(url);
    request.addHeader("Accept-Encoding", "gzip");
    

    @JulianReschke pointed out that there can be a case of:

    "Content-Encoding" : "gzip, gzip"
    

    so extended server code will be:

    InputStream in = response.getEntity().getContent();
    Header encodingHeader = response.getFirstHeader("Content-Encoding");
    
    String gzip = "gzip";
    if (encodingHeader != null) {
        String encoding = encodingHeader.getValue().toLowerCase();
        int firstGzip = encoding.indexOf(gzip);
        if (firstGzip > -1) {
          in = new GZIPInputStream(in);
          int secondGzip = encoding.indexOf(gzip, firstGzip + gzip.length());
          if (secondGzip > -1) {
            in = new GZIPInputStream(in);
          }
        }
    }
    

    I suppose that nginx is used as load balancer or proxy, so you need to set tomcat to do decompression.

    Add following attributes to the Connector in server.xml on Tomcat,

    
    

    Accepting gziped requests in tomcat is a different story. You'll have to put a filter in front of your servlets to enable request decompression. You can find more about that here.

提交回复
热议问题