欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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)文章

  • Spring框架之IOC介紹講解

    Spring框架之IOC介紹講解

    IOC-Inversion of Control,即控制反轉(zhuǎn)。它不是什么技術(shù),而是一種設(shè)計思想。這篇文章將為大家介紹一下Spring控制反轉(zhuǎn)IOC的原理,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • 基于SSM實現(xiàn)學生管理系統(tǒng)

    基于SSM實現(xiàn)學生管理系統(tǒng)

    這篇文章主要為大家詳細介紹了基于SSM實現(xiàn)學生管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-12-12
  • Java編程實現(xiàn)逆波蘭表達式代碼示例

    Java編程實現(xiàn)逆波蘭表達式代碼示例

    本文主要對Java算法逆波蘭表達式的相關(guān)內(nèi)容作了介紹,涉及逆波蘭表達式的定義已經(jīng)在Java中的實現(xiàn),具有一定參考價值,需要的朋友可以了解下。
    2017-10-10
  • java中BeanUtils.copyProperties的用法(超詳細)

    java中BeanUtils.copyProperties的用法(超詳細)

    本文介紹了BeanUtils.copyProperties()方法的使用,包括其功能、用法、注意事項和示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-08-08
  • springBoot前后端分離項目中shiro的302跳轉(zhuǎn)問題

    springBoot前后端分離項目中shiro的302跳轉(zhuǎn)問題

    這篇文章主要介紹了springBoot前后端分離項目中shiro的302跳轉(zhuǎn)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java計算一個數(shù)加上100是完全平方數(shù),加上168還是完全平方數(shù)

    Java計算一個數(shù)加上100是完全平方數(shù),加上168還是完全平方數(shù)

    這篇文章主要介紹了Java計算一個數(shù)加上100是完全平方數(shù),加上168還是完全平方數(shù),需要的朋友可以參考下
    2017-02-02
  • Eclipse項目有紅感嘆號的解決方法

    Eclipse項目有紅感嘆號的解決方法

    這篇文章主要為大家詳細介紹了Eclipse項目有紅感嘆號的解決方法,給出了Eclipse項目有紅感嘆號的原因,以及如何解決?,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • java字節(jié)碼框架ASM操作字節(jié)碼的方法淺析

    java字節(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)系

    這篇文章主要介紹了詳談jpa中表的@OneToMany等關(guān)聯(lián)關(guān)系,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java使用Collections.sort()排序的示例詳解

    Java使用Collections.sort()排序的示例詳解

    這篇文章主要介紹了Java使用Collections.sort()排序的示例詳解,Collections.sort(list, new PriceComparator());的第二個參數(shù)返回一個int型的值,就相當于一個標志,告訴sort方法按什么順序來對list進行排序。對此感興趣的可以了解一下
    2020-07-07

最新評論