HttpsURLConnection跳过SSL证书发送请求

x33g5p2x  于2021-10-17 转载在 其他  
字(3.5k)|赞(0)|评价(0)|浏览(460)

在Java的编程世界里面,我们有的时候,会经常访问一些HTTPS的网站,那么访问这些HTTPS的网站的时候,如果当前这个网站是自己企业内部的已知的网站,或者我们信任的网站,这个时候,我们为了编写程序的方便,就不需要把当前网站的服务器的根证书以及中间证书导入到JKS里面,让在程序在调用HTTP协议的时候对服务器的服务器名和证书名进行对比

解决办法: 跳过SSL证书,将下面部分代码添加到你的类或者方法中就能跳过证书了

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtils {

    // 忽略整个类SSL证书请求
// static {
// try {
// trustAllHttpsCertificates();
// HttpsURLConnection.setDefaultHostnameVerifier
// (
// (urlHostName, session) -> true
// );
// } catch (Exception e) {
// }
// }

    public static String doGet(String mainUrl, String sysID, String pKey, Map<String, String> params) throws Exception {

        StringBuffer queryString = new StringBuffer();
        String utf8 = "UTF-8";
        String random = URLEncoder.encode(java.util.UUID.randomUUID().toString(), utf8);
        String code = URLEncoder.encode(pKey+ random, utf8);
        queryString.append("Random=");
        queryString.append(random);
        queryString.append("&");
        queryString.append("Code=");
        queryString.append(code);
        queryString.append("&");
        queryString.append("SysID=");
        queryString.append(sysID);
        queryString.append("&");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            queryString.append(entry.getKey());
            queryString.append("=");
            queryString.append(URLEncoder.encode(entry.getValue(), utf8));
            queryString.append("&");
        }

        String query = queryString.toString();
        query = query.substring(0, query.length() - 1);

        String url = mainUrl + "?" + query;
        System.out.println(url);
        URL serverUrl = new URL(url);

        //-----忽略这个请求相关证书。
        trustAllHttpsCertificates();
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        //-------

        HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection();
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP GET Request Failed with Error code : " + connection.getResponseCode());
        }

        BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        String output;
        String result = "";
        while ((output = responseBuffer.readLine()) != null) {
            result += output;
        }
        connection.disconnect();

        return result;
    }

    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }
}

相关文章