摘要:如果服务器证书这两者不合法而我们又必须让其校验通过,则可以自己实现。这个属性是新加的属性,因为目前版本是可以共享连接池的。请求获取数据的超时时间,单位毫秒。如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
/**
com.alibaba fastjson 1.2.47 org.apache.httpcomponents httpclient 4.5.9 commons-lang commons-lang 2.6 org.projectlombok lombok 1.16.18
*/
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
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.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.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
public class httpClientUtil {
//采用绕过验证的方式处理https请求 // SSLContext sslcontext = createIgnoreVerifySSL(); public static CloseableHttpClient getIgnoeSSLClient() throws Exception { SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }).build(); //CloseableHttpClient client = HttpClients.createDefault();*/ //设置协议http和https对应的处理socket链接工厂的对象 RegistrysocketFactoryRegistry = RegistryBuilder. create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslContext)) .build(); //HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(rrrr); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); //创建httpClient CloseableHttpClient client = HttpClients.custom() .setSSLContext(sslContext).setConnectionManager(connManager). setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); return client; } public final static void main(String[] args) throws Exception { CloseableHttpClient httpClient =getIgnoeSSLClient(); CloseableHttpClient httpClient1 = null; // try { /* // 加载自定义的keystore // SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(new File("D:/java/IdeaProjects/test/src/main/resources/certs/my.keystore"), "123456".toCharArray()).build(); SSLContext sslContext = createIgnoreVerifySSL(); // 默认的域名校验类为DefaultHostnameVerifier,比对服务器证书的AlternativeName和CN两个属性。 // 如果服务器证书这两者不合法而我们又必须让其校验通过,则可以自己实现HostnameVerifier。 SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { // 我们可以重写域名校验逻辑 return true; } }); // 一个httpClient对象对于https仅会选用一个SSLConnectionSocketFactory // 至少在4.5.3和4.5.4中,如果给HttpClient对象设置ConnectionManager,我们必须在PoolingHttpClientConnectionManager的构造方法中传入Registry, // 并将https对应的工厂设置为我们自己的SSLConnectionSocketFactory对象,因为在DefaultHttpClientConnectionOperator.connect()中,逻辑是从这里找SSLConnectionSocketFactory的。 PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder. create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory) .build()); connectionManager.setMaxTotal(20); connectionManager.setDefaultMaxPerRoute(20); httpClient1 = HttpClients.custom() // 不在connectionManager中注册,仅在这里设置SSLConnectionSocketFactory是无效的,详见build()内部逻辑,在connectionManager不为null时,不会使用里的SSLConnectionSocketFactory .setSSLSocketFactory(sslConnectionSocketFactory) .setConnectionManager(connectionManager) .build();*/ /* httpClient = getIgnoeSSLClient(); HttpGet httpGet = new HttpGet("https://www.12306.cn"); System.out.println("Executing request " + httpGet.getRequestLine()); CloseableHttpResponse response = httpClient.execute(httpGet); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8")); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != httpClient) { httpClient.close(); } } catch (Exception e) { e.printStackTrace(); } }*/ String body = ""; /* //采用绕过验证的方式处理https请求 SSLContext sslcontext = createIgnoreVerifySSL(); //设置协议http和https对应的处理socket链接工厂的对象 Registry socketFactoryRegistry = RegistryBuilder. create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); HttpClients.custom().setConnectionManager(connManager); //创建自定义的httpclient对象 CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build(); //CloseableHttpClient client = HttpClients.createDefault();*/ try{ //创建post方式请求对象 HttpPost httpPost = new HttpPost("https://www.douban.com/service/apikey/apply");//https://api.douban.com/v2/book/1220562 //指定报文头Content-type、User-Agent httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2"); //setConnectTimeout:设置连接超时时间,单位毫秒。 //setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。 //setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build(); httpPost.setConfig( requestConfig); //apikey: "0b2bdeda43b5688921839c8ecb20399b" Map params = new HashMap (); params.put("apikey","0b2bdeda43b5688921839c8ecb20399b"); StringEntity stringEntity = new StringEntity(JSON.toJSONString(params),"utf-8"); httpPost.setEntity(stringEntity); //执行请求操作,并拿到结果(同步阻塞) CloseableHttpResponse response = httpClient.execute(httpPost); //获取结果实体 HttpEntity entity = response.getEntity(); if (entity != null) { //按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, "UTF-8"); } EntityUtils.consume(entity); //释放链接 response.close(); System.out.println("body:" + body); }finally{ httpClient.close(); } } public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sc = SSLContext.getInstance("SSLv3"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法 X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } public void checkServerTrusted( java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; sc.init(null, new TrustManager[] { trustManager }, null); return sc; }
}
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/75739.html
摘要:序本文从里头摘出访问的源码,展示一下怎么用去访问。其中指定要不要检验,如果不校验,则是使用小结使用不去验证,但是可能存在风险构造 序 本文从spring cloud netflix zuul里头摘出httpclient访问https/http的源码,展示一下怎么用httpclient去访问https。 newConnectionManager protected PoolingHttp...
摘要:此时我想到了福尔摩斯说过的一句话当你排除掉各种不可能出现的情况之后,剩下的情况无论多么难以置信,都是真相。福尔摩斯冷静下来想一想,这个线程,有可能静悄悄地退出了吗,没留下半点异常日志从理论上来说,不可能。配置建议最后,附上一份配置建议。 1、事发 我们有个视频处理程序,基于 SpringBoot,会启动几个线程来跑。要退出程序时,会发送一个信号给程序,每个线程收到信号后会平滑退出,等全...
摘要:问题最近项目上面遇到和对接,测试库他们使用的是,但是正式库使用的是。之前没有做过,在网上找过好多文章,最后还是借鉴别人的,自己重新封装之后才在项目上面使用。以上是我在项目上面使用的,没有添加全部的代码,但是对应的方法都是可以使用的。 问题: 最近项目上面遇到和App对接,测试库他们使用的是 HTTP,但是正式库使用的是 HTTPS。之前没有做过,在网上找过好多文章,最后还是借鉴别人的,...
摘要:鉴于它还处在,如果不是着急使用,建议还是使用的,它是遵循规范的,使用起来更加方便。貌似要在版本才支持。揭秘让支持协议如何启用命令支持 序 本文主要研究下JEP 110: HTTP/2 Client (Incubator) 基本实例 sync get /** * --add-modules jdk.incubator.httpclient * @throws ...
阅读 3885·2021-11-22 09:34
阅读 1475·2021-11-04 16:10
阅读 1705·2021-10-11 10:59
阅读 3258·2019-08-30 15:44
阅读 2022·2019-08-30 13:17
阅读 3428·2019-08-30 11:05
阅读 728·2019-08-29 14:02
阅读 2603·2019-08-26 13:34