java中調用https請求忽略ssl證書認證代碼示例
更新時間:2024年10月26日 09:07:33 作者:新時代農民~
在網絡請求中經常會遇到需要忽略證書認證的情況,這篇文章主要介紹了java中調用https請求忽略ssl證書認證的相關資料,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下
1、獲取httpclient,忽略證書認證
public static CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有證書 public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); // 創(chuàng)建主機名驗證器,用于繞過主機名驗證 HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; // 創(chuàng)建 SSL 連接套接字工廠,將自定義的 SSL 上下文和主機名驗證器應用于 HTTPS 連接 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); // 創(chuàng)建自定義的 CloseableHttpClient 實例,將 SSL 連接套接字工廠應用于 HTTP 客戶端 return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return HttpClients.createDefault(); }
2、使用put請求調用
public static String put(String url, Map<String, String> header, String param) throws Exception { String result = ""; StringEntity entity = new StringEntity(param, "utf-8"); CloseableHttpClient httpClient = null; try { httpClient = createSSLClientDefault(); HttpPut httpPut = new HttpPut(url); if (MapUtils.isNotEmpty(header)) { for (Map.Entry<String, String> entry : header.entrySet()) { httpPut.addHeader(entry.getKey(), entry.getValue()); } } if (entity != null) { entity.setContentType("application/json; charset=utf-8"); httpPut.setEntity(entity); } LogUtil.info("開始請求https接口:" + url ); HttpResponse httpResponse = httpClient.execute(httpPut); LogUtil.info("put請求返回httpResponse結果:" + httpResponse); HttpEntity resEntity = httpResponse.getEntity(); result = EntityUtils.toString(resEntity, "UTF-8"); LogUtil.info("put請求返回結果:" + result); } catch (Exception e) { throw e; } finally { if (httpClient != null) { httpClient.close(); } } return result; }
總結
到此這篇關于java中調用https請求忽略ssl證書認證的文章就介紹到這了,更多相關java調用https請求忽略ssl認證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java使用ffmpeg和mencoder實現(xiàn)視頻轉碼
這篇文章主要為大家詳細介紹了Java使用ffmpeg和mencoder實現(xiàn)視頻轉碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12新版IDEA使用Spring Initializr創(chuàng)建工程的兩種方法
這篇文章主要介紹了新版IDEA使用Spring Initializr創(chuàng)建工程(兩種方法,官方工具和IDEA),文中通過代碼示例和圖文結合的方式給大家講解的非常詳細,具有一定的參考價值,需要的朋友可以參考下2024-10-10MyBatis利用攔截器實現(xiàn)數(shù)據(jù)脫敏詳解
現(xiàn)代網絡環(huán)境中,敏感數(shù)據(jù)的處理是至關重要的,敏感數(shù)據(jù)包括個人身份信息、銀行賬號、手機號碼等,所以本文主要為大家詳細介紹了MyBatis如何利用攔截器實現(xiàn)數(shù)據(jù)脫敏,希望對大家有所幫助2023-11-11Java Annotation(Java 注解)的實現(xiàn)代碼
本篇文章介紹了,Java Annotation(Java 注解)的實現(xiàn)代碼。需要的朋友參考下2013-05-05