最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java如何實(shí)現(xiàn)通過證書訪問Https請(qǐng)求

 更新時(shí)間:2022年01月30日 09:02:02   作者:王紹樺  
這篇文章主要介紹了Java如何實(shí)現(xiàn)通過證書訪問Https請(qǐng)求,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Java通過證書訪問Https請(qǐng)求

創(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)用測(cè)試

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請(qǐng)求
    	HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    	// 創(chuàng)建SSLContext對(duì)象,并使用我們指定的信任管理器初始化 
    	TrustManager[] tm = { new MyX509TrustManager(keystoreFile,keystorePass) }; 
    	SSLContext sslContext = SSLContext.getInstance("TLS"); 
    	sslContext.init(null, tm, new java.security.SecureRandom()); 
    	// 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象 
    	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=測(cè)試";
        PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream(),"UTF-8"));
        out.print(param);          
        out.flush();
        out.close();
        //讀取請(qǐng)求返回值
	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請(qǐng)求繞過證書檢測(cè)

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;
    }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

上蔡县| 哈巴河县| 文成县| 大兴区| 铜鼓县| 永定县| 安乡县| 彭水| 汝阳县| 巴楚县| 河南省| 呼伦贝尔市| 八宿县| 淳安县| 横峰县| 綦江县| 当阳市| 临桂县| 惠来县| 威远县| 胶州市| 泗阳县| 军事| 许昌县| 藁城市| 平南县| 吐鲁番市| 博爱县| 花垣县| 盘山县| 敖汉旗| 新兴县| 从化市| 莱芜市| 平原县| 清丰县| 濉溪县| 奉贤区| 郎溪县| 依安县| 清徐县|