>  기사  >  HTTPS 인증서 확인 예외를 해결하는 방법은 무엇입니까?

HTTPS 인증서 확인 예외를 해결하는 방법은 무엇입니까?

青灯夜游
青灯夜游원래의
2020-04-16 10:33:533926검색

HTTPS 인증서 확인이 비정상인데, 확인에 실패하면 어떻게 해야 하나요? 다음 글에서는 HTTPS 요청 확인 인증서 실패에 대한 해결 방법을 소개하겠습니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

HTTPS 인증서 확인 예외를 해결하는 방법은 무엇입니까?

오류: 요청한 대상에 대한 유효한 인증 경로를 찾을 수 없습니다

해결책:

1. 인증서를 로컬 인증서 저장소로 가져옵니다

2. 모든 SSL 인증서를 신뢰하세요

가장 좋은 해결책은 신뢰입니다. 모든 SSL 인증서는 때로는 인증서를 매번 수동으로 가져오는 것이 매우 번거롭기 때문입니다. 이제 메소드가 캡슐화되었습니다. openConnection에 연결할 때 인증서를 무시하세요.

SslUtils.java

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
public class SslUtils {private static void trustAllHttpsCertificates() throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[1];
    TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
 
static class miTM implements TrustManager,X509TrustManager {
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
 
    public boolean isServerTrusted(X509Certificate[] certs) {
        return true;
    }
 
    public boolean isClientTrusted(X509Certificate[] certs) {
        return true;
    }
 
    public void checkServerTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
        return;
    }
 
    public void checkClientTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
        return;
    }
}
 
/**
 * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
 * @throws Exception
 */
public static void ignoreSsl() throws Exception{
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            return true;
        }
    };
    trustAllHttpsCertificates();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
 
}

SslTest.java:

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;
 
public class SslTest {
     
    public String getRequest(String url,int timeOut) throws Exception{
        URL u = new URL(url);
        if("https".equalsIgnoreCase(u.getProtocol())){
            SslUtils.ignoreSsl();
        }
        URLConnection conn = u.openConnection();
        conn.setConnectTimeout(timeOut);
        conn.setReadTimeout(timeOut);
        return IOUtils.toString(conn.getInputStream());
    }
     
    public String postRequest(String urlAddress,String args,int timeOut) throws Exception{
        URL url = new URL(urlAddress);
        if("https".equalsIgnoreCase(url.getProtocol())){
            SslUtils.ignoreSsl();
        }
        URLConnection u = url.openConnection();
        u.setDoInput(true);
        u.setDoOutput(true);
        u.setConnectTimeout(timeOut);
        u.setReadTimeout(timeOut);
        OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(), "UTF-8");
        osw.write(args);
        osw.flush();
        osw.close();
        u.getOutputStream();
        return IOUtils.toString(u.getInputStream());
    }
     
    public static void main(String[] args) {
        try {
            SslTest st = new SslTest();
            String a = st.getRequest("https://xxx.com/login.action", 3000);
            System.out.println(a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

더 많은 관련 지식을 알고 싶다면 PHP 중국어 웹사이트를 주목해주세요!

위 내용은 HTTPS 인증서 확인 예외를 해결하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.