【Http】Apache HttpClient 4.5实现https
全部信任的
import org.apache.commons.collections.MapUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
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.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class HttpsUtils {private static final String HTTP = "http";private static final String HTTPS = "https";private static SSLConnectionSocketFactory sslsf = null;private static PoolingHttpClientConnectionManager cm = null;private static SSLContextBuilder builder = null;static {try {builder = new SSLContextBuilder();// 全部信任 不做身份鉴定builder.loadTrustMaterial(null, new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {return true;}});sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();cm = new PoolingHttpClientConnectionManager(registry);cm.setMaxTotal(200);//max connection} catch (Exception e) {e.printStackTrace();}}/*** httpClient post请求* @param url 请求url* @param header 头部信息* @param param 请求参数 form提交适用* @param entity 请求实体 json/xml提交适用* @return 可能为空 需要处理* @throws Exception**/public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception {String result = "";CloseableHttpClient httpClient = null;try {httpClient = getHttpClient();HttpPost httpPost = new HttpPost(url);// 设置头信息if (MapUtils.isNotEmpty(header)) {for (Map.Entry<String, String> entry : header.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 设置请求参数if (MapUtils.isNotEmpty(param)) {List<NameValuePair> formparams = new ArrayList<NameValuePair>();for (Map.Entry<String, String> entry : param.entrySet()) {//给参数赋值formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);httpPost.setEntity(urlEncodedFormEntity);}// 设置实体 优先级高if (entity != null) {httpPost.setEntity(entity);}HttpResponse httpResponse = httpClient.execute(httpPost);int statusCode = httpResponse.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {HttpEntity resEntity = httpResponse.getEntity();result = EntityUtils.toString(resEntity);} else {readHttpResponse(httpResponse);}} catch (Exception e) {throw e;} finally {if (httpClient != null) {httpClient.close();}}return result;}public static CloseableHttpClient getHttpClient() throws Exception {CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).setConnectionManagerShared(true).build();return httpClient;}public static String readHttpResponse(HttpResponse httpResponse)throws ParseException, IOException {StringBuilder builder = new StringBuilder();// 获取响应消息实体HttpEntity entity = httpResponse.getEntity();// 响应状态builder.append("status:" + httpResponse.getStatusLine());builder.append("headers:");HeaderIterator iterator = httpResponse.headerIterator();while (iterator.hasNext()) {builder.append("\t" + iterator.next());}// 判断响应实体是否为空if (entity != null) {String responseString = EntityUtils.toString(entity);builder.append("response length:" + responseString.length());builder.append("response content:" + responseString.replace("\r\n", ""));}return builder.toString();}
}
重写检验函数的
package com.space.utils.http;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
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.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;/*** http请求工具类* @author zhuzhe* @date 2018/5/3 11:46*/
public class HttpUtils {/*** get** @param host* @param path** @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doGet(String host, String path,Map<String, String> headers,Map<String, String> querys)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpGet request = new HttpGet(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** post form** @param host* @param path** @param headers* @param querys* @param bodys* @return* @throws Exception*/public static HttpResponse doPost(String host, String path,Map<String, String> headers,Map<String, String> querys,Map<String, String> bodys)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (bodys != null) {List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");request.setEntity(formEntity);}return httpClient.execute(request);}/*** Post String** @param host* @param path** @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path,Map<String, String> headers,Map<String, String> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Post stream** @param host* @param path** @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path,Map<String, String> headers,Map<String, String> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Put String* @param host* @param path** @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path,Map<String, String> headers,Map<String, String> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Put stream* @param host* @param path** @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path,Map<String, String> headers,Map<String, String> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Delete** @param host* @param path** @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doDelete(String host, String path,Map<String, String> headers,Map<String, String> querys)throws Exception {HttpClient httpClient = wrapClient(host,path);HttpDelete request = new HttpDelete(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** 构建请求的 url* @param host* @param path* @param querys* @return* @throws UnsupportedEncodingException*/private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {StringBuilder sbUrl = new StringBuilder();if (!StringUtils.isBlank(host)) {sbUrl.append(host);}if (!StringUtils.isBlank(path)) {sbUrl.append(path);}if (null != querys) {StringBuilder sbQuery = new StringBuilder();for (Map.Entry<String, String> query : querys.entrySet()) {if (0 < sbQuery.length()) {sbQuery.append("&");}if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {sbQuery.append(query.getValue());}if (!StringUtils.isBlank(query.getKey())) {sbQuery.append(query.getKey());if (!StringUtils.isBlank(query.getValue())) {sbQuery.append("=");sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));}}}if (0 < sbQuery.length()) {sbUrl.append("?").append(sbQuery);}}return sbUrl.toString();}/*** 获取 HttpClient* @param host* @param path* @return*/private static HttpClient wrapClient(String host,String path) {HttpClient httpClient = HttpClientBuilder.create().build();if (host != null && host.startsWith("https://")) {return sslClient();}else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {return sslClient();}return httpClient;}/*** 在调用SSL之前需要重写验证方法,取消检测SSL* 创建ConnectionManager,添加Connection配置信息* @return HttpClient 支持https*/private static HttpClient sslClient() {try {// 在调用SSL之前需要重写验证方法,取消检测SSLX509TrustManager trustManager = new X509TrustManager() {@Override public X509Certificate[] getAcceptedIssuers() {return null;}@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}};SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);ctx.init(null, new TrustManager[] { trustManager }, null);SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);// 创建RegistryRequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https",socketFactory).build();// 创建ConnectionManager,添加Connection配置信息PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();return closeableHttpClient;} catch (KeyManagementException ex) {throw new RuntimeException(ex);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}}/*** 将结果转换成JSONObject* @param httpResponse* @return* @throws IOException*/public static JSONObject getJson(HttpResponse httpResponse) throws IOException {HttpEntity entity = httpResponse.getEntity();String resp = EntityUtils.toString(entity, "UTF-8");EntityUtils.consume(entity);return JSON.parseObject(resp);}
}
原文链接:https://blog.csdn.net/star890124/article/details/87938384
【Http】Apache HttpClient 4.5实现https相关推荐
- okhttp3测试框架_easy-okhttp: 这是一个对okhttp3进行封装的工具,提供了更为便捷的方法调用。目的是为了替换难用的apache HttpClient。...
easy-okhttp 简介 项目easy-okhttp是对okhttp网络框架(https://github.com/square/okhttp)上层封装, 支持文件上传和下载,表单(含文件)提交, ...
- 新旧apache HttpClient 获取httpClient方法
在apache httpclient 4.3版本中对很多旧的类进行了deprecated标注,通常比较常用的就是下面两个类了. DefaultHttpClient -> CloseableHtt ...
- 用Apache HttpClient实现URL重定向
分享一下我老师大神的人工智能教程.零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow <用Apac ...
- Apache HttpClient 4 3开发指南
<Apache HttpClient 4.3开发指南> 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs 一.概述 Apache HttpCli ...
- Apache HttpClient连接池泄露问题排查
Apache HttpClient连接池泄露问题排查 问题背景 业务系统主要的业务是一个数据聚合管理平台,其中系统有一个功能是同步所有资源(简称 大同步) 业务同步数据请求数据工具是适配 Apache ...
- Apache HttpClient
文章目录 Apache HttpClient 简介 Apache HttpClient特性 使用流程 使用实例 -END- Apache HttpClient 简介 HttpClient 是 Apac ...
- Apache HttpClient 5 笔记: SSL, Proxy 和 Multipart Upload
Apache HttpClient 5 最近要在非SpringBoot环境调用OpenFeign接口, 需要用到httpclient, 注意到现在 HttpClient 版本已经到 5.2.1 了. ...
- Apache HttpClient 客户端使用详解、文件上传、文件下载
目录 HttpClient 概述与下载 Http Get 请求(文件下载) Http POST 请求(文件上传) Http Put 请求 Http Delete 请求 异步执行请求 HttpClien ...
- 一个封装的使用Apache HttpClient进行Http请求(GET、POST、PUT等)的类。
一个封装的使用Apache HttpClient进行Http请求(GET.POST.PUT等)的类. import com.qunar.payment.gateway.front.channel.mp ...
最新文章
- day02 cssjs 基础
- 每个程序员都应该读的书
- 包浆网图分分钟变高清,伪影去除、细节恢复更胜前辈AI,下载可玩|腾讯ARC实验室出品...
- Java - 为什么要使用接口编程【转】
- python 反转列表的3种方式
- CSDN粉丝可见回来了!
- 使用docker registry建立私有镜像仓库
- VS2008中开发智能设备程序的一些总结
- Android 底部上拉抽屉view
- HMC支持管理服务器数量及适合POWER6服务器的HMC型号
- 扫地机器人水箱背景_你真的懂扫地机器人吗?这些不为人知的小细节值得一看...
- Java全栈学习路线
- Halcon教程十四:训练自己的模型然后识别相似的图像
- 毕业实习笔记——WRF模式入门(Cygwin版)
- 科学道德与学风-2021雨课堂答案-第10章
- c语言程序设计数独,C语言求解数独
- 保险精算--第五周作业
- iOS 字体转换
- 树模型(1)-入门指南
- OpManager 实时网络监控
热门文章
- 魅族17将配备GaN氮化镓充电器:快充安全又高效
- 苹果悬赏100万美元找漏洞 辞职的理由找到了!
- 中国移动将于11月1日公布5G套餐价格,北京地区已建5000个5G基站
- 小米电视双十一大降价:55寸仅1399元
- 奥斯卡“最佳国际电影”奖,《哪吒之魔童降世》申请出战!
- “不差钱”华为刷屏 拟募资60亿!
- 这下真“火”了!为涨粉在红绿灯底座上跳舞 两女子被行拘...
- LMS赛区公告:DG战队因假赛被永久除名
- 刘强东凌晨发内部信:取消底薪不是为了降低工资
- 拼多多回应“鼓励刷单”:文章描述有歧义 已删除