前言

最近项目正在筹备上线,发现 HttpClient 中的很多类和方法都已经过时了,虽然并不影响功能的实现,但是看着确实让人捉急,所以,索性抽了点时间把它给改了。今天就来分享一下。。。

之前的代码

先看看之前的代码吧:以下是之前的过时代码(部分,完整代码在文章末会贴出git地址)

private static void sslClient(HttpClient httpClient) {try {SSLContext ctx = SSLContext.getInstance("TLS");X509TrustManager tm = new X509TrustManager() {@Override public X509Certificate[] getAcceptedIssuers() {return null;}@Override public void checkClientTrusted(X509Certificate[] xcs, String str) {}@Override public void checkServerTrusted(X509Certificate[] xcs, String str) {}};ctx.init(null, new TrustManager[] { tm }, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx);ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = httpClient.getConnectionManager();SchemeRegistry registry = ccm.getSchemeRegistry();registry.register(new Scheme("https", 443, ssf));} catch (KeyManagementException ex) {throw new RuntimeException(ex);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}}

修改后的代码

    /*** 在调用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);}}

完整代码(HttpUtils)

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);}
}

这是我的github:  https://github.com/zhuzhegithub/utils

转载请务必保留此出处(原作者):https://blog.csdn.net/zhuzhezhuzhe1

版权声明:本文为原创文章,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。

https://blog.csdn.net/zhuzhezhuzhe1

HttpClient4.5实现http与https请求,解决之前方法过时问题相关推荐

  1. android 解决getColor()方法过时

    今天,简单讲讲android里如何解决getColor()方法过时的问题. 之前,我写博客讲了程序员需要解决过时的方法的问题,Google会提供过时函数的替代函数,程序员有责任找到替代函数,并且解决过 ...

  2. 解决FragmentPagerAdapter方法过时

    用到ViewPager和TabLayout时,发现FragmentPagerAdapter()方法过时 class MyAdapter(fm: FragmentManager?, fragmentLi ...

  3. fiddler无法获取Android端https请求解决办法

    或者Fiddler2出现 creation of the root certificate was not successful 错误 1,设置fiddler代理 2,使用设备进入网址:localho ...

  4. Android 7.0解决抓取不到https请求的问题

    Android 7.0解决抓取不到https请求的问题 参考文章: (1)Android 7.0解决抓取不到https请求的问题 (2)https://www.cnblogs.com/meitian/ ...

  5. python https请求报错:SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] 解决方法

    python爬虫,使用requests库发送https请求报错:SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] 解决方法: imp ...

  6. Android 使用自带的HttpClient进行https请求出现403的解决过程记录

    2019独角兽企业重金招聘Python工程师标准>>> 出现的过程 最近在用程序模拟一个web站的https登录,然后进行一些后续操作的小玩意.先使用java程序写测试代码,测试通过 ...

  7. android 监听本机网络请求_fiddler如何抓取https请求实现fiddler手机抓包-证书安装失败100%解决...

    一.HTTP协议和HTTPS协议. (1) HTTPS协议=HTTP协议+SSL协议,默认端口:443 (2) HTTP协议(HyperText Transfer Protocol):超文本传输协议. ...

  8. 关于IOS由于Dropbox被封,https请求不好用的解决办法

    最近研究IOS的In-House安装方法,好不容易申请下来了企业级证书,也使用了Dropbox的网盘来支持苹果的In-House安装方法,也给客户展示了,下载的地址也给客户了.没过几天,坑爹的天朝把D ...

  9. java用HttpURLConnection发起HTTPS请求并跳过SSL证书,解决:unable to find valid certification path to requested targ

    java用HttpURLConnection发起HTTPS请求并跳过SSL证书 问题出现:unable to find valid certification path to requested ta ...

最新文章

  1. rpm 安装ipython
  2. string和byte[]的相互转换
  3. PHP独特学习模式_php基础知识
  4. css怎样定义div大小,css如何设置div大小
  5. 【计算几何】bzoj2338 [HNOI2011]数矩形
  6. Support Web Application Projects
  7. ES6最详细/易懂教程
  8. 深度linux iso镜像,深度 Deepin 15 正式版 ISO 镜像下载 - 精美易用适合国人学习的国产 Linux 发行版......
  9. Halcon算子实现——Texture_Laws
  10. VC中GDI绘图技术基础知识:hdc设备环境句柄,坐标系
  11. 缺失值处理的三种方法
  12. 【其他】【RQNOJ】吉祥数
  13. (更新)Raspberry Pi OS Lite/Full arm64 Bullseye安装Cutefish桌面
  14. 肖星老师《一本书读懂财报》经典语句摘录(上)概念篇
  15. 《麦肯锡意识》前言 解决问题的战略模型-思维导图
  16. 数据挖掘I 电力窃漏电用户自动识别
  17. 交通路口信号灯c语言编程,PLC十字路口的交通灯控制编程实例
  18. 智能家居软文营销以受众为中心,创作有说服力的文案
  19. C语言中的字符变量和字符常量
  20. 阿里云国际站服务器Linux系统磁盘管理怎么操作?

热门文章

  1. 电气EPlan软件第六章到第十章的学习
  2. Otsu(大津法,最大类间方差法)
  3. 简单易用的公司网页模板,助您快速建站
  4. 上手百度地图--开放平台必懂API使用场合(PC端)
  5. python爬取新闻存入数据库_python爬取数据存入数据库
  6. 游戏开发之UDK引擎介绍和模型导入
  7. (超详细)语音信号处理之特征提取
  8. [激光器原理与应用-7]: 半导体制冷片与TEC温控器
  9. 使用springer nature模板页眉显示标题太长超出页面解决
  10. Android Toast控件