httpClient 请求深度封装

  • 因为项目需求,需要集成http请求,就采用了非常火的httpclient,因为httpclient需要设置的东西比较多,在开发中,有些人不知道怎么调用,因此对其进行了二次封装,使用起来就简单的多了.废话少说上代码

package com.rjhcsoft.credit.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.*;
import org.apache.http.concurrent.Cancellable;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Map;

public class HttpRequestUtil {

    public static HttpBuilder builder() {
        return new HttpBuilder();
    }

    private static class HttpBuilder {
        private CloseableHttpClient httpClient;
        private String url;
        private HttpRequestBase httpRequestBase;
        private HttpMethod httpMethod;
        private Map<String, String> headers;
        private Map<String, String> params;
        private HttpEntity httpEntity;
        private InputStream inputStream;
        private String entity;
        private Charset charset;
        private String contentType;
        private Cancellable cancellable;

        HttpBuilder() {
            httpClient = HttpClients.createDefault();
        }

        public HttpBuilder get() {
            return get(null);
        }

        public HttpBuilder get(String url) {
            setUrl(url);
            setMethod(HttpMethod.GET);
            return this;
        }

        public HttpBuilder post() {
            return post(null);
        }

        public HttpBuilder post(String url) {
            setUrl(url);
            setMethod(HttpMethod.POST);
            return this;
        }

        public HttpBuilder put() {
            return put(null);
        }

        public HttpBuilder put(String url) {
            setUrl(url);
            setMethod(HttpMethod.PUT);
            return this;
        }

        public HttpBuilder delete() {
            return delete(null);
        }

        public HttpBuilder delete(String url) {
            setUrl(url);
            setMethod(HttpMethod.DELETE);
            return this;
        }

        public HttpBuilder setUrl(String url) {
            if (url != null)
                this.url = url;
            return this;
        }

        public HttpBuilder setMethod(HttpMethod method) {
            if (method != null) this.httpMethod = method;
            else this.httpMethod = HttpMethod.GET;
            return this;
        }

        public HttpBuilder setParams(Map<String, String> params) {
            this.params = params;
            return this;
        }

        public HttpBuilder setHeaders(Map<String, String> headers) {
            this.headers = headers;
            return this;
        }

        public HttpBuilder setCancellable(Cancellable cancellable) {
            this.cancellable = cancellable;
            return this;
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param entity
         * @return
         */
        public HttpBuilder setEntity(HttpEntity entity) {
            this.httpEntity = entity;
            return this;
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param entity
         * @return
         */
        public HttpBuilder setEntity(String entity) {
            return setEntity(entity, null, null);
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param entity
         * @param charset 编码
         * @return
         */
        public HttpBuilder setEntity(String entity, Charset charset) {
            return setEntity(entity, charset, null);
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param contentType
         * @param entity
         * @return
         */
        public HttpBuilder setEntity(String entity, String contentType) {
            return setEntity(entity, null, contentType);
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param entity
         * @param charset 编码
         * @return
         */
        public HttpBuilder setEntity(String entity, Charset charset, String contentType) {
            this.entity = entity;
            this.charset = charset;
            this.contentType = contentType;
            return this;
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param is
         * @return
         */
        public HttpBuilder setEntity(InputStream is) {
            return setEntity(is, null);
        }

        /**
         * 设置请求体,此同名方法只能存在一个,若多个存在,则只有第一个有效
         *
         * @param contentType
         * @param is
         * @return
         */
        public HttpBuilder setEntity(InputStream is, String contentType) {
            this.contentType = contentType;
            this.inputStream = is;
            return this;
        }

        /**
         * 实际执行方法,此方法应放最后执行
         *
         * @param callback
         */
        public void execute(Callback callback) {
            if (url == null) throw new RuntimeException("URL UNDEFINED!");
            if (httpMethod == null) throw new RuntimeException("HttpMethod UNDEFINED!");
            try {
                URI uri = new URI(url);
                switch (httpMethod) {
                    case GET:
                        httpRequestBase = new HttpGet(uri);
                        break;
                    case POST:
                        httpRequestBase = new HttpPost(uri);
                        if (httpEntity != null) {
                            ((HttpPost) httpRequestBase).setEntity(httpEntity);
                        } else if (entity != null) {
                            StringEntity stringEntity = null;
                            if (charset == null) {
                                stringEntity = new StringEntity(entity);
                            } else {
                                stringEntity = new StringEntity(entity, charset);
                            }
                            ((HttpPost) httpRequestBase).setEntity(stringEntity);
                            if (contentType != null)
                                stringEntity.setContentType(contentType);
                        } else if (inputStream != null) {
                            BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
                            basicHttpEntity.setContent(inputStream);
                            if (contentType != null) basicHttpEntity.setContentType(contentType);
                            ((HttpPost) httpRequestBase).setEntity(basicHttpEntity);
                        }
                        break;
                    case DELETE:
                        httpRequestBase = new HttpDelete(uri);
                        break;
                    case PUT:
                        httpRequestBase = new HttpPut(uri);
                        if (httpEntity != null) {
                            ((HttpPut) httpRequestBase).setEntity(httpEntity);
                        } else if (entity != null) {
                            StringEntity stringEntity = null;
                            if (charset == null) {
                                stringEntity = new StringEntity(entity);
                            } else {
                                stringEntity = new StringEntity(entity, charset);
                            }
                            ((HttpPut) httpRequestBase).setEntity(stringEntity);
                            if (contentType != null)
                                stringEntity.setContentType(contentType);
                        } else if (inputStream != null) {
                            BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
                            basicHttpEntity.setContent(inputStream);
                            if (contentType != null) basicHttpEntity.setContentType(contentType);
                            ((HttpPut) httpRequestBase).setEntity(basicHttpEntity);
                        }
                        break;
                }
                if (headers != null && !headers.isEmpty()) {
                    for (String key : headers.keySet()) {
                        httpRequestBase.addHeader(key, headers.get(key));
                    }
                }
                if (params != null && !params.isEmpty()) {
                    HttpParams httpParams = new BasicHttpParams();
                    for (String key : params.keySet()) {
                        httpParams.setParameter(key, params.get(key));
                    }
                    httpRequestBase.setParams(httpParams);
                }
                if (cancellable != null) httpRequestBase.setCancellable(cancellable);
                CloseableHttpResponse response = httpClient.execute(httpRequestBase);
                callback.callback(response);
            } catch (Exception e) {
                callback.exception(e);
            } finally {
                callback.finallz();
                if (httpClient != null) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public enum HttpMethod {
        GET, POST, PUT, DELETE
    }

    public interface Callback {
        /**
         * 此方法为请求返回之后的处理,交给客户端处理,
         *
         * @param response 返回报文实体
         */
        void callback(HttpResponse response) throws Exception;

        /**
         * 无论execute方法是否出异常,此方法都会最终执行,所以,如果打开io流,请在这里关闭
         */
        void finallz();

        /**
         * 当execute方法出异常的时候,会调用此方法,
         */
        void exception(Exception e);
    }
}

  • 测试
 /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
                HttpRequestUtil.builder().get("https://www.baidu.com").execute(new Callback() {
            InputStream is = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            @Override
            public void callback(HttpResponse response) throws Exception {
                
                    int code = response.getStatusLine().getStatusCode();
                    if (code == 200) {
                        is = response.getEntity().getContent();
                        isr = new InputStreamReader(is);
                        br = new BufferedReader(isr);
                        char[] chars = new char[1024];
                        int m = -1;
                        while ((m = br.read(chars)) > 0) {
                            String s = new String(chars, 0, m);
                            System.out.println(s);
                        }
                    }
            }

            @Override
            public void finallz() {
                try {
                    if(br!=null)
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (isr!=null) {
                    try {
                        isr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is!=null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void exception(Exception e) {
                throw new RuntimeException(e);
            }
        });

    }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页