2019年8月26日 星期一

[JAVA] 當java程式忽略憑證問題(PKIX問題)


方法一:
在 httpConnection.setRequestProperty 程式碼後,即可使用以下程式碼...






 TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){

             public X509Certificate[] getAcceptedIssuers(){return null;}

             public void checkClientTrusted(X509Certificate[] certs, String authType){}

             public void checkServerTrusted(X509Certificate[] certs, String authType){}

         }};



         // Install the all-trusting trust manager

         try {

             SSLContext sc = SSLContext.getInstance("TLS");

             sc.init(null, trustAllCerts, new SecureRandom());

             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

         } catch (Exception e) {

             ;

         }





方法二:

在public static void main(String[] args)程式碼前加入

public class TrustAnyHostnameVerifier implements HostnameVerifier {

  public boolean verify(String hostname, SSLSession session) {

   return true;

  }

 }

並在 httpConnection.setRequestProperty 程式碼後,加入以下程式碼
**注意: MyProject01(). 的部份是專案名稱,就是最外層的public class MyProject01{ 的名字

((HttpsURLConnection) httpConnection).setHostnameVerifier(new MyProject01().new TrustAnyHostnameVerifier());




沒有留言: