集册 Java实例教程 通过apache http压缩客户端GZip内容

通过apache http压缩客户端GZip内容

欢马劈雪     最近更新时间:2020-01-02 10:19:05

481
通过apache http进行客户端GZip内容压缩
/* 来 自 N o w  J a v a  .   c o m*/


import java.io.IOException;


import org.apache.http.Header;

import org.apache.http.HttpEntity;

import org.apache.http.HttpException;

import org.apache.http.HttpRequest;

import org.apache.http.HttpRequestInterceptor;

import org.apache.http.HttpResponse;

import org.apache.http.HttpResponseInterceptor;

import org.apache.http.client.entity.GzipDecompressingEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;
/** 
 来自 N  o w  J a v a . c o m**/

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.protocol.HttpContext;

import org.apache.http.util.EntityUtils;


public class ClienGZipContentCompression {


    public static void main(String[] args) {

        HttpClientBuilder hb = HttpClients.custom();


        hb.addInterceptorFirst(new HttpRequestInterceptor() {

            @Override

            public void process(HttpRequest req, HttpContext ctx)

                    throws HttpException, IOException {

                if (!req.containsHeader("Accept-Encoding")) {

                    req.addHeader("Accept-Encoding", "gzip");

                }

            }

        });


        hb.addInterceptorFirst(new HttpResponseInterceptor() {

            @Override

            public void process(HttpResponse res, HttpContext ctx)

                    throws HttpException, IOException {

                HttpEntity entity = res.getEntity();

                if (entity != null) {

                    Header contentEncoding = res

                            .getFirstHeader("Content-Encoding");

                    if (contentEncoding != null

                            && contentEncoding.getValue().equalsIgnoreCase(

                                    "gzip")) {

                        res.setEntity(new GzipDecompressingEntity(entity));

                        return;

                    }

                }

            }

        });


        HttpGet htpGet = new HttpGet("http://www.apache.org");

        try (CloseableHttpClient hc = hb.build();

                CloseableHttpResponse res = hc.execute(htpGet)) {

            System.out.println("executing request " + htpGet.getURI());


            System.out.println("----------------------------------------");

            System.out.println(res.getStatusLine());

            System.out.println(res.getLastHeader("Content-Encoding"));

            System.out.println(res.getLastHeader("Content-Length"));

            System.out.println(
展开阅读全文