Java如何實現(xiàn)通過證書訪問Https請求
更新時間:2022年01月30日 09:02:02 作者:王紹樺
這篇文章主要介紹了Java如何實現(xiàn)通過證書訪問Https請求,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
Java通過證書訪問Https請求
創(chuàng)建證書管理器類
import java.io.FileInputStream; import java.security.KeyStore; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class MyX509TrustManager implements X509TrustManager{ X509TrustManager sunJSSEX509TrustManager; MyX509TrustManager(String keystoreFile,String pass) throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystoreFile), pass.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE"); tmf.init(ks); TrustManager tms [] = tmf.getTrustManagers(); for (int i = 0; i < tms.length; i++) { if (tms[i] instanceof X509TrustManager) { sunJSSEX509TrustManager = (X509TrustManager) tms[i]; return; } } throw new Exception("Couldn't initialize"); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { sunJSSEX509TrustManager.checkClientTrusted(chain, authType); } catch (CertificateException excep) { excep.printStackTrace(); } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { sunJSSEX509TrustManager.checkServerTrusted(chain, authType); } catch (CertificateException excep) { excep.printStackTrace(); } } @Override public X509Certificate[] getAcceptedIssuers() { return sunJSSEX509TrustManager.getAcceptedIssuers(); } }
調(diào)用測試
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; public class HttpsCaTest { public static void main(String[] args) throws Exception { String keystoreFile = "D:\\tomcat.keystore"; String keystorePass = "ldysjhj"; //設(shè)置可通過ip地址訪問https請求 HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); // 創(chuàng)建SSLContext對象,并使用我們指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager(keystoreFile,keystorePass) }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tm, new java.security.SecureRandom()); // 從上述SSLContext對象中得到SSLSocketFactory對象 SSLSocketFactory ssf = sslContext.getSocketFactory(); String urlStr = "https://192.168.1.10/login_queryLkBySfmc.htm"; URL url = new URL(urlStr); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setSSLSocketFactory(ssf); con.setRequestMethod("POST"); // 設(shè)置以POST方式提交數(shù)據(jù) con.setDoInput(true); // 打開輸入流,以便從服務(wù)器獲取數(shù)據(jù) con.setDoOutput(true);// 打開輸出流,以便向服務(wù)器提交數(shù)據(jù) //設(shè)置發(fā)送參數(shù) String param = "sfmc=測試"; PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream(),"UTF-8")); out.print(param); out.flush(); out.close(); //讀取請求返回值 InputStreamReader in = new InputStreamReader(con.getInputStream(),"UTF-8"); BufferedReader bfreader = new BufferedReader(in); String result = ""; String line = ""; while ((line = bfreader.readLine()) != null) { result += line; } System.out.println("result:"+result); } }
工具類
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; public class NullHostNameVerifier implements HostnameVerifier{ @Override public boolean verify(String hostname, SSLSession session) { return true; } }
https請求繞過證書檢測
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.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; public class HttpsClientUtil { private static CloseableHttpClient httpClient; static { try { SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build(); RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build(); } catch (Exception e) { e.printStackTrace(); } } public String doPost(String url, String jsonString) { try { HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(jsonString, "utf-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; } }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java中BeanUtils.copyProperties的用法(超詳細)
本文介紹了BeanUtils.copyProperties()方法的使用,包括其功能、用法、注意事項和示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08springBoot前后端分離項目中shiro的302跳轉(zhuǎn)問題
這篇文章主要介紹了springBoot前后端分離項目中shiro的302跳轉(zhuǎn)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Java計算一個數(shù)加上100是完全平方數(shù),加上168還是完全平方數(shù)
這篇文章主要介紹了Java計算一個數(shù)加上100是完全平方數(shù),加上168還是完全平方數(shù),需要的朋友可以參考下2017-02-02java字節(jié)碼框架ASM操作字節(jié)碼的方法淺析
這篇文章主要給大家介紹了關(guān)于java字節(jié)碼框架ASM如何操作字節(jié)碼的相關(guān)資料,文中通過示例代碼介紹的很詳細,有需要的朋友可以參考借鑒,下面來一起看看吧。2017-01-01詳談jpa中表的@OneToMany等關(guān)聯(lián)關(guān)系
這篇文章主要介紹了詳談jpa中表的@OneToMany等關(guān)聯(lián)關(guān)系,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12Java使用Collections.sort()排序的示例詳解
這篇文章主要介紹了Java使用Collections.sort()排序的示例詳解,Collections.sort(list, new PriceComparator());的第二個參數(shù)返回一個int型的值,就相當于一個標志,告訴sort方法按什么順序來對list進行排序。對此感興趣的可以了解一下2020-07-07