广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java如何实现通过证书访问Https请求
  • 363
分享到

Java如何实现通过证书访问Https请求

2024-04-02 19:04:59 363人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录Java通过证书访问https请求创建证书管理器类调用测试工具类Https请求绕过证书检测Java通过证书访问Https请求 创建证书管理器类 import java.io.Fi

Java通过证书访问Https请求

创建证书管理器类

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

调用测试

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";
    	//设置可通过ip地址访问https请求
    	HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    	// 创建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"); // 设置以POST方式提交数据
    	con.setDoInput(true); // 打开输入流,以便从服务器获取数据
    	con.setDoOutput(true);// 打开输出流,以便向服务器提交数据
    	//设置发送参数
        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;
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Java如何实现通过证书访问Https请求

本文链接: https://www.lsjlt.com/news/138041.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作