首页 > 编程知识 正文

org.apache.http.impl.client 如何请求 HTTPS 的接口?

时间:2023-05-06 18:24:09 阅读:149503 作者:1339

背景类型: HTTPS工具类: org.apache.http.impl.client发现网络上发现的许多信息不真实,无法真正完成HTTPS接口的请求,经过测试

要点忽略安全证书验证,3358www.Sina.com/版本代码示例设置以下方法:TLSHTTP

HTTPS

importorg.Apache.http.config.registry; importorg.Apache.http.config.registry builder; importorg.Apache.http.conn.socket.connectionsocketfactory; importorg.Apache.http.conn.socket.plainconnectionsocketfactory; importorg.Apache.http.conn.SSL.noophostnameverifier; importorg.Apache.http.conn.SSL.sslconnectionsocketfactory; importorg.Apache.http.conn.SSL.trustselfsignedstrategy; importorg.Apache.http.impl.client.closeablehttpclient; importorg.Apache.http.impl.client.http clients; importorg.Apache.http.impl.conn.poolinghttpclientconnectionmanager; importorg.Apache.http.SSL.sslcontext builder; import javax.net.ssl.SSLContext; import Java.security.keymanagementexception; import Java.security.keystore exception; import Java.security.nosuchalgorithmexception; publicclasshttpsclient { publiccloseablehttpclientgetcloseablehttpsclient () } throwsnosuchalgorithmexception,KeyStoreException keystore exception eymanagementexception//sslcontextbuildersslcontextbuilder=newsslcontextbuilder ().loadtrustmattmation new TrustSelfSignedStrategy () ).setsecurerandom ) ) null ).useprotocol ) tlsv1.3 ); //sslcontextsslcontextsslcontext=builder.build (; //sslconnectionsocketfactorysslconnectionsocketfactory=newsslconnectionsocketfactory (//) registryregistryconnectionsocketfactoryregistry=registry builder.connectionsocketfactorycreate ().register (http newplainew ) //connectionmanagerpoolinghttpclientconnectionmanagercm=newpoolinghttpclientconnectionmanager (registry ); cm.setmaxtotal(2000; //clientcloseablehttpclienthttpclient=http clients.custom ().setsslsocketfactory (sslconnectionsocketfactory ).setct

onManager(cm) .build(); return httpClient; }}

法二

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.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.SSLConnectionSocketFactory;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.util.EntityUtils;import org.junit.Test;import org.springframework.boot.test.context.SpringBootTest;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import java.io.IOException;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.cert.CertificateException;@SpringBootTestpublic class HttpsClientTest2 { /** * 获取SSL套接字对象 重点重点:设置tls协议的版本 * * @return */ public static SSLContext createIgnoreVerifySSLContext() { SSLContext sslContext = null;// 创建套接字对象 try { sslContext = SSLContext.getInstance("TLSv1.3");//指定TLS版本 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // 实现X509TrustManager接口,用于绕过验证 X509TrustManager trustManager = new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; try { sslContext.init(null, new TrustManager[] { trustManager }, null);//初始化sslContext对象 } catch (KeyManagementException e) { e.printStackTrace(); } return sslContext; } /** * 获取https协议请求对象 * * @return */ public static CloseableHttpClient getCloseableHttpsClient() { // 采用绕过验证的方式处理https请求 SSLContext sslcontext = createIgnoreVerifySSLContext(); // 设置协议http和https对应的处理socket链接工厂的对象 Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext)) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); // 创建自定义的httpsclient对象 CloseableHttpClient client = HttpClients.custom() .setConnectionManager(connManager) .build(); return client; }} 测试 // 省略main class, 根据自己的情况引入即可 public void httpsSupportTest() throws Exception { CloseableHttpClient httpClient = getCloseableHttpsClient(); CloseableHttpResponse response = null; String result = ""; // 测试 https String urlHttps = "https://my-https-url"; String secretKeyHttps = "my-secret-key"; // 构造 request HttpGet getRequest_1 = new HttpGet(urlHttps); getRequest_1.setHeader("secretKey", secretKeyHttps); // 配置 request RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(120000) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(120000) // socket读写超时时间(单位毫秒) .setSocketTimeout(120000) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true).build(); getRequest_1.setConfig(requestConfig); try { response = httpClient.execute(getRequest_1); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { result = EntityUtils.toString(responseEntity); System.out.println("result: " + result); } } catch (IOException e) { e.printStackTrace(); } } 备注: 以上方法,本质上是忽略了安全证书的校验,违背了 HTTPS 的使用初衷,不建议用到生产中。如果出现提示 TLSv1.3 is not supported 不支持的报错,请检查 JDK 的版本,因为 TLSv1.3 对 JDK 的小版本有要求(参考4) 参考 https://zhuanlan.zhihu.com/p/86980940https://github.com/apache/httpcomponents-client/blob/5.1.x/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientCustomSSL.javahttps://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3http://openjdk.java.net/jeps/332

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。