<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连接时跳过证书验证,默认信任所有的站点.

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

import org.apache.commons.collections.MapUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
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.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /*
* Http/Https请求的工具类
* */
public class HttpClientUtils {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
static StringBuffer cookielocal= new StringBuffer();//保存cookie值 ,使得在新建httpClient时保持会话
//static CloseableHttpClient httpClient = null; 可以使用同一个client规避不同client需要添加cookie
/*
接下来在登陆的的请求中调用 setCookieStore(HttpResponse httpResponse)方法,保存会话cookie;
如果后面出现新的httpclient时,给请求添加请求头,例如:
httpGet.setHeader("cookie",cookielocal.substring(0,cookielocal.length()-1).toString());
*/ 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.getHttpClient();
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> pairList = new ArrayList<>();
for(Map.Entry<String,String> stringStringEntry : params.entrySet()){
pairList.add(new BasicNameValuePair((String)stringStringEntry.getKey(),(String)stringStringEntry.getValue()));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairList, Consts.UTF_8);
httpPost.setEntity(urlEncodedFormEntity);
}
//实体设置
if(httpEntity != null){
httpPost.setEntity(httpEntity);
}
//发起请求
httpResponse = httpClient.execute(httpPost);
setCookieStore(httpResponse);
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> stringStringMap, 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.getHttpClient();
//请求参数信息
if (MapUtils.isNotEmpty(params)) {
url = url + buildUrl(params);
}
HttpGet httpGet = new HttpGet(url);
System.err.println("获取的cookie值:"+cookielocal.substring(0,cookielocal.length()-1).toString());
httpGet.setHeader("cookie",cookielocal.substring(0,cookielocal.length()-1).toString());//设定cookie信息在post请求中已经过去
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(50000)//连接超时
.setConnectionRequestTimeout(50000)//请求超时
.setSocketTimeout(50000)//套接字连接超时
.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.isEmpty(result)) {
result = result.substring(0, result.length() - 1);//去掉结尾的&连接符
}
return result;
} public static void setCookieStore(HttpResponse httpResponse) { Header[] headers = httpResponse.getHeaders("Set-Cookie");
for(Header header : headers) {
HeaderElement[] headerElementArray = header.getElements();
for (HeaderElement headerElement : headerElementArray) { if (null != headerElement.getValue()) {
// 获取cookie并保存
cookielocal.append(headerElement.getName() + "=" + headerElement.getValue() + ";");
} }
} }

写个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. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  2. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. Java 发送 Https 请求工具类 (兼容http)

    依赖 jsoup-1.11.3.jar <dependency> <groupId>org.jsoup</groupId> <artifactId>js ...

  5. Https通信工具类

    记录一个在微信开发中用到的https通信工具类,以后会用到的. 用于https通信的证书信任管理器 import java.security.cert.CertificateException; im ...

  6. HttpClient 之 发送Https请求

    HttpClient包是一个优秀的Http请求的开源jar. 本文Http工具类的封装基于HttpClient,封装后的工具类支持Https请求. 但是由于项目的需要快速的实现,以下代码还可能会有点过 ...

  7. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  8. 【原创】标准HTTP请求工具类

    以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...

  9. Http请求工具类(Java原生Form+Json)

    package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...

随机推荐

  1. HashMap 实现原理解析

    概要 HashMap 最早出现在 JDK 1.2 中,底层基于散列算法实现.HashMap 允许 null 键和 null 值,在计算哈键的哈希值时,null 键哈希值为 0.HashMap 并不保证 ...

  2. Orleans 文档记录

    Orleans 官方文档:官方文档 http://dotnet.github.io/orleans/index.html Orleans 中文文档:中文文档 https://orleanscn.git ...

  3. 从5个方面让你真正了解Java内存模型

    前言 首先我们在了解java内存模型之前先看一下计算机内存模型,理解了计算机内存模型的话后面在看JMM就会简单的多. 计算机内存 计算机是由CPU.主存.磁盘等组成的(简单引出问题熬)我们都知道计算机 ...

  4. iOS Charts 折线图框架的基本使用

    1. 导入框架 通过 cocoapods 管理应用程序时,在 Podfile 文件中,use_frameworks! 的使用区别如下: 使用 use_frameworks! 时 dynamic fra ...

  5. 《Java算法》排序算法-快速排序

    排序算法-快速排序: /** * 给定一个数组:按照从小到大排序. * 思路: * 1. 获取第一个数放入临时变量data,将大于data的数放右边,小于data的数放在左边. * 2. data左边 ...

  6. Mysql数据库的主从与主主

    前言: 首先,我们得知道我们为什么要做数据库的主从与主主,而后,再讨论他们的优劣与特点:为什么要做主从呢?因为Mysql数据库没有增量备份的机制,当数据量太大的时候备份是个难以解决的问题.但是mysq ...

  7. 常用数据结构之ArrayList

    前言 ArrayList想必是广大Java程序员开发时最常用的数据结构了,但不一定对其原理都有了解,今天我将结合ArrayList的源码对其进行讲解.本文将围绕ArrayList主要特性(包括适用场景 ...

  8. IDEA 解决Project SDK is not defined

    IDEA 解决Project SDK is not defined 问题如下: 点击蓝字Setup SDK. 点击configure... 点击+,选择JDK. 选择jdk所在路径,点击确定. 选中, ...

  9. Gradle for Android ( 构建变体 )

    链接: http://77blogs.com/?p=38 https://www.cnblogs.com/tangZH/p/10999060.html 有时候我们一个app需要有不同的版本,不同的版本 ...

  10. 林克的小本本之——记一些基础的linux命令

    查看shell cat /etc/shells 查看系统支持的shell echo $SHELL 查看目前正在使用的shell 快捷键 Ctrl+a 跳到行首 Ctrl+e 跳到行尾 Ctrl+u 删 ...