本文涉及到的主要依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>

针对4.5版本的Httpclient采用连接池的方式管理连接

package com.wx4jdemo.controller.utils;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
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.ssl.SSLContextBuilder;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Https忽略证书
 */
public class SSLClientCustom {private static final String HTTP = "http";
    private static final String HTTPS = "https";
    private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;//连接池管理类
    private static SSLContextBuilder sslContextBuilder = null;//管理Https连接的上下文类

    static {try {sslContextBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {@Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
//                    信任所有站点 直接返回true
                    return true;
                }});
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslConnectionSocketFactory).build();
            poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registryBuilder);
            poolingHttpClientConnectionManager.setMaxTotal(200);
        } catch (NoSuchAlgorithmException e) {e.printStackTrace();
        } catch (KeyStoreException e) {e.printStackTrace();
        } catch (KeyManagementException e) {e.printStackTrace();
        }}/**
     * 获取连接
     *
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient getHttpClinet() throws Exception {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(poolingHttpClientConnectionManager).setConnectionManagerShared(true).build();
        return httpClient;
    }
}

Registry类注册Http/Https连接,并且当是https连接时跳过证书验证,默认信任所有的站点.

接下来就是发起请求的工具类代码编写

package com.wx4jdemo.controller.utils;

import org.apache.commons.collections.MapUtils;
import org.apache.http.*;
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.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http/Https请求的工具类
 */
public class HttpClientUtils {private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * 发送post请求
     *
     * @param url:请求地址
     * @param header:请求头参数
     * @param params:表单参数  form提交
     * @param httpEntity   json/xml参数
     * @return
     */
    public static String doPostRequest(String url, Map<String, String> header, Map<String, String> params, HttpEntity httpEntity) {String resultStr = "";
        if (StringUtils.isEmpty(url)) {return resultStr;
        }CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {httpClient = SSLClientCustom.getHttpClinet();
            HttpPost httpPost = new HttpPost(url);
            //请求头header信息
            if (MapUtils.isNotEmpty(header)) {for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
                }}//请求参数信息
            if (MapUtils.isNotEmpty(params)) {List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {paramList.add(new BasicNameValuePair(stringStringEntry.getKey(), stringStringEntry.getValue()));
                }UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpPost.setEntity(urlEncodedFormEntity);
            }//实体设置
            if (httpEntity != null) {httpPost.setEntity(httpEntity);
            }//发起请求
            httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {HttpEntity httpResponseEntity = httpResponse.getEntity();
                resultStr = EntityUtils.toString(httpResponseEntity);
                logger.info("请求正常,请求地址:{},响应结果:{}", url, resultStr);
            } else {StringBuffer stringBuffer = new StringBuffer();
                HeaderIterator headerIterator = httpResponse.headerIterator();
                while (headerIterator.hasNext()) {stringBuffer.append("\t" + headerIterator.next());
                }logger.info("异常信息:请求地址:{},响应状态:{},请求返回结果:{}", url, httpResponse.getStatusLine().getStatusCode(), stringBuffer);
            }} catch (Exception e) {e.printStackTrace();
        } finally {HttpClientUtils.closeConnection(httpClient, httpResponse);
        }return resultStr;
    }
    public static String doGetRequest(String url, Map<String, String> header, Map<String, String> params) {String resultStr = "";
        if (StringUtils.isEmpty(url)) {return resultStr;
        }CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {httpClient = SSLClientCustom.getHttpClinet();
            //请求参数信息
            if (MapUtils.isNotEmpty(params)) {url = url + buildUrl(params);
            }HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)//连接超时
                    .setConnectionRequestTimeout(5000)//请求超时
                    .setSocketTimeout(5000)//套接字连接超时
                    .setRedirectsEnabled(true).build();//允许重定向
            httpGet.setConfig(requestConfig);
            if (MapUtils.isNotEmpty(header)) {for (Map.Entry<String, String> stringStringEntry : header.entrySet()) {httpGet.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
                }}//发起请求
            httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {resultStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
                logger.info("请求地址:{},响应结果:{}", url, resultStr);
            } else {StringBuffer stringBuffer = new StringBuffer();
                HeaderIterator headerIterator = httpResponse.headerIterator();
                while (headerIterator.hasNext()) {stringBuffer.append("\t" + headerIterator.next());
                }logger.info("异常信息:请求响应状态:{},请求返回结果:{}", httpResponse.getStatusLine().getStatusCode(), stringBuffer);
            }} catch (Exception e) {e.printStackTrace();
        } finally {HttpClientUtils.closeConnection(httpClient, httpResponse);
        }return resultStr;
    }/**
     * 关掉连接释放资源
     */
    private static void closeConnection(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {if (httpClient != null) {try {httpClient.close();
            } catch (IOException e) {e.printStackTrace();
            }}if (httpResponse != null) {try {httpResponse.close();
            } catch (IOException e) {e.printStackTrace();
            }}}
/**
 * 构造get请求的参数
 *
 * @return
 */
private static String buildUrl(Map<String, String> map) {if (MapUtils.isEmpty(map)) {return "";
    }StringBuffer stringBuffer = new StringBuffer("?");
    for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {stringBuffer.append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
    }String result = stringBuffer.toString();
    if (StringUtils.isNotEmpty(result)) {result = result.substring(0, result.length() - 1);//去掉结尾的&连接符
    }return result;
    }
}

写个main函数测试

   public static void main(String[] args) {String httpsUrl = "https://github.com/";HttpClientUtils.doGetRequest(httpsUrl, null, null);String hpptsPostUrl = "https://www.cnblogs.com/Mr-Rocker/p/6229652.html";HttpClientUtils.doPostRequest(hpptsPostUrl, null, null, null);Map<String, String> params = new HashMap<>();params.put("ie", "utf-8");params.put("wd", "java");params.put("tn", "92032424_hao_pg");Map<String, String> header = new HashMap<>();header.put("User-Agent:", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");HttpClientUtils.doGetRequest("https://www.baidu.com/s", header, params);}

本文章在参考网上案例的基础上编写,仅作个人学习如有侵权请联系删除,谢谢.

--结尾语

             有志者、事竟成,破釜沉舟,百二秦关终属楚;          苦心人、天不负,卧薪尝胆,三千越甲可吞吴。 

HttpClient发起Http/Https请求工具类相关推荐

  1. http和https请求工具类

    https请求 @Slf4j public class HttpPostUtils {public static int RESPONSE_STATUS_OK = 0;public static JS ...

  2. Java Https请求工具类

    个人技术网站 欢迎关注 由于微信API接口建议使用Https请求方式 而且过不久就废弃http请求方式了 所以提供以下Https工具类 public class SSLClient extends D ...

  3. .NET WebApi调用微信接口Https请求工具类

    .NET WebApi调用微信接口Https请求工具类 using System; using System.Collections.Generic; using System.IO; using S ...

  4. 发送http和https请求工具类 Json封装数据

    在一些业务中我们可要调其他的接口(第三方的接口) 这样就用到我接下来用到的工具类. 用这个类需要引一下jar包的坐标 <dependency><groupId>org.jsou ...

  5. 【Java】HTTP请求工具类

    前言 在工作中可能存在要去调用其他项目的接口,这篇文章我们实现在Java代码中实现调用其他项目的接口. 本章内容: 创建一个携带参数的POST请求,去请求其他项目的接口并返回数据. 附加HTTP请求工 ...

  6. HTTP POST 请求工具类

    HTTP/HTTPS POST 请求工具类 Maven pom.xml 引入依赖 <dependency><groupId>org.apache.httpcomponents& ...

  7. Http请求工具类:Get/Post

    第一种 import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.htt ...

  8. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  9. 【Http请求工具类】

    Http请求工具类(待优化) 添加相关依赖 <!-- 发送http请求依赖 --><dependency><groupId>commons-io</group ...

最新文章

  1. 一个流畅的iOS图表框架PNChart
  2. 新版pycharm,亮瞎我的狗眼
  3. 数据中心或许会成为未来5G最强大的技术支撑
  4. (转)FTP的PORT(主动模式)和PASV(被动模式)
  5. 从 Netflix 到 Spring Cloud Alibaba 差距不知一点点
  6. 揭秘支撑双 11 买买买背后的硬核黑科技!
  7. 魅族Flyme5系统内置原生铃声免费下载
  8. 当子元素设置position absolute的时,父元素必须设置position属性
  9. 大屏scroll滚动轴样式
  10. Openwrt源码LuCI应用完整说明
  11. Java开发常见英文单词(带音标翻译)
  12. Kylo 之 spark-job-profiler 源码阅读
  13. 计算机公共课3-字处理软件Word 2010
  14. matlab如何编newton-raphson,Matlab中的Newton Raphsons方法?
  15. 游侠随笔:关于业务型数据库审计 有图有真相
  16. Nicholas C. Zakas谈怎样才能成为优秀的前端工程师
  17. 第十届泰迪杯数据挖掘B题:电力系统负荷预测分析--解题思路与部分代码03
  18. 多条件统计利器COUNTIFS函数的使用方法
  19. matlab做混频,基于MATLAB的混频测试
  20. php根据淘宝短链接获取商品ID

热门文章

  1. xml建模包括以下_()是专业建模语言。A.XMLB.UMLC.VC++D.JAVA - 信管网
  2. 分享50个漂亮的双屏桌面壁纸资源(上篇)
  3. 南宁师范大学计算机学院校区,师院新生攻略之五合校区(2017版)
  4. CTO俱乐部系列之四:3G和移动互联网的CTO俱乐部活动
  5. 黑科技丨资源搜索神器
  6. Lattice系列FPGA之SerDes
  7. 计算机丢失mfc110d.dll,msvcp110d.dll
  8. 尝试使用以5W1H分析法来学习5W1H分析法
  9. 智能变电站远程监控解决方案
  10. 软件著作权证书有什么作用