美文网首页
HTTP 请求封装

HTTP 请求封装

作者: 黑曼巴yk | 来源:发表于2020-07-25 09:42 被阅读0次

前言

我们在做项目的时候经常需要用到HTTP请求,但是org.apache.http.client不满足HTTPS的请求,这里我们需要经常封装自己的请求库


import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.liberate.core.constant.LiberateConsts;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

@Slf4j
public final class HttpUtils {
    public static final String HTTP_METHOD_GET = "GET";
    public static final String HTTP_METHOD_POST = "POST";
    public static final String HTTP_METHOD_PUT = "PUT";
    public static final String HTTP_METHOD_DELETE = "DELETE";
    private static final int DEFAULT_CONNECT_TIMEOUT = 5;
    private static final int DEFAULT_READ_TIMEOUT = 30;

    private static PoolingHttpClientConnectionManager connectionManager;

    private static int connectTimeout = DEFAULT_CONNECT_TIMEOUT;
    private static int readTimeout = DEFAULT_READ_TIMEOUT;

    private HttpClientTools() {
    }

    private static synchronized void init() {
        if (connectionManager == null) {
            try {
                Registry<ConnectionSocketFactory> connectionSocketFactory = RegistryBuilder
                        .<ConnectionSocketFactory> create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", new SSLConnectionSocketFactory(
                                new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                                    @Override
                                    public boolean isTrusted(X509Certificate[] arg0, String arg1)
                                            throws CertificateException {
                                        return true;
                                    }
                                }).build(),
                                new HostnameVerifier() {
                                    @Override
                                    public boolean verify(String hostname, SSLSession session) {
                                        return true;
                                    }
                                }))
                        .build();
                connectionManager = new PoolingHttpClientConnectionManager(connectionSocketFactory);
            } catch (Exception e) {
                log.warn("HttpClientTools PoolingHttpClientConnectionManager with connectionSocketFactory init occur error");
                e.printStackTrace();
                connectionManager = new PoolingHttpClientConnectionManager();
            }

            connectionManager.setMaxTotal(LiberateConsts.MAX_CONN_TOTAL);
            connectionManager.setDefaultMaxPerRoute(LiberateConsts.MAX_CONN_PER_ROUTE);
        }
    }

    private static CloseableHttpClient getHttpClient() {
        init();

        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout * 1000)
                .setConnectTimeout(connectTimeout * 1000).setSocketTimeout(readTimeout * 1000).build();
        return HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
                .build();
    }

    /**
     * 设置自定义超时策略
     *
     * @param connectTimeout
     * @param readTimeout
     */
    public static void setCustomTimeout(int connectTimeout, int readTimeout) {
        HttpClientTools.connectTimeout = connectTimeout;
        HttpClientTools.readTimeout = readTimeout;
    }

    /**
     * POST请求
     * 
     * @param url
     * @param heads
     * @param params
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String post(String url, Map<String, String> heads, Map<String, String> params)
            throws IllegalStateException, IOException {
        return post(url, heads, params, "utf-8");
    }

    /**
     * POST请求
     * 
     * @param url
     * @param heads
     * @param params
     * @param encoding
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String post(String url, Map<String, String> heads, Map<String, String> params, String encoding)
            throws IllegalStateException, IOException {
        HttpPost httpPost = new HttpPost(url);

        if (MapUtils.isNotEmpty(heads)) {
            Iterator<String> it = heads.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                httpPost.addHeader(key, heads.get(key));
            }
        }
        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
        if (MapUtils.isNotEmpty(params)) {
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(list, encoding));
        }

        return getResult(httpPost);
    }

    /**
     *
     * @param url
     * @param body
     * @throws IllegalStateException
     * @throws IOException
     */
    public static String post(String url, JSONObject body)
        throws IllegalStateException, IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity stringEntity = new StringEntity(body.toJSONString(), "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        return getResult(httpPost);
    }

    /**
     * GET请求
     * 
     * @param url
     * @param heads
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url, Map<String, String> heads, Map<String, String> params)
            throws ClientProtocolException, IOException {
        String p = null;
        StringBuilder sb = new StringBuilder();
        if (MapUtils.isNotEmpty(params)) {
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
            p = sb.substring(0, sb.length() - 1);
        }

        HttpGet httpGet = new HttpGet(url + (p == null ? "" : ("?" + p)));

        if (MapUtils.isNotEmpty(heads)) {
            for (Map.Entry<String, String> head : heads.entrySet()) {
                httpGet.addHeader(head.getKey(), head.getValue());
            }
        }

        return getResult(httpGet);
    }

    /**
     * 处理Http请求
     * @param request
     * @return
     * @throws IOException
     */
    private static String getResult(HttpRequestBase request) throws IOException {
        String result = StringUtils.EMPTY;
        CloseableHttpClient httpClient = getHttpClient();
        try(CloseableHttpResponse response = httpClient.execute(request)) {
            // response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // long len = entity.getContentLength();// -1 表示长度未知
                result = EntityUtils.toString(entity, "UTF-8");
                response.close();
                // httpClient.close();
            }
        } catch (ClientProtocolException e) {
            log.error("getResult request ClientProtocolException", e);
        } catch (IOException e) {
            log.error("getResult request IOException", e);
        } finally {

        }
        return result;
    }

    /**
     * 判断异常是否是连接超时的异常
     * 
     * @param ex
     * @return
     */
    public static boolean isTimeoutException(Exception ex) {
        // 读取超时
        if (ex instanceof SocketTimeoutException) {
            return true;
        }
        // 连接超时
        if (ex instanceof ConnectTimeoutException) {
            return true;
        }
        // httpclient插件的连接超时异常
        if (ex instanceof ConnectionPoolTimeoutException) {
            return true;
        }
        if (ex instanceof SocketException) {
            return true;
        }
        return false;
    }
}

相关文章

  • springcloud ribbon 的简单使用

    RestTemplate 对http请求通信的封装,封装了http请求,方便的请求http接口。 Ribbon r...

  • 封装HTTP请求

    每次访问网址,需要配置网络连接的很多属性(e.i. 请求方法、连接超时时间、读取资源超时时间等),很麻烦,所以这里...

  • 封装http请求

    import 'package:dio/dio.dart'; import 'dart:async'; impor...

  • HTTP 请求封装

    前言 我们在做项目的时候经常需要用到HTTP请求,但是org.apache.http.client不满足HTTPS...

  • JavaEE-HttpServletRequest总结

    HttpServletRequest: 封装了Http请求内容(请求行, 请求头, 请求体) 1.HTTP请求行和...

  • Koa(五、源码浅析)

    基础http请求 针对http基础请求简单封装 效果上面两者相同,下面继续封装 js的getter和setter ...

  • curl发送请求方法封装request

    //使用url封装请求方法 //封装可以请求http和https //可以发送get和post的请求方式 func...

  • TCP/HTTP/Socket

    HTTP和Scoket通信的区别。 http是客户端用http协议进行请求,发送请求时候需要封装http请求头,并...

  • NO.39 WebServer代码实现

    1)先定义HTTP协议中相关信息的类 2)封装Http请求相关内容: 3)封装Http响应 4)处理客户端请求 5...

  • js http请求封装

网友评论

      本文标题:HTTP 请求封装

      本文链接:https://www.haomeiwen.com/subject/ugkplktx.html