Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: userc865b
Added: Jul 15, 2018 2:38 PM
Views: 0
Tags: java
when android does not accept a certificate:
  1. // https://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https/6378872
  2.  
  3. import java.security.SecureRandom;
  4. import java.security.cert.X509Certificate;
  5.  
  6. import javax.net.ssl.HostnameVerifier;
  7. import javax.net.ssl.HttpsURLConnection;
  8. import javax.net.ssl.SSLContext;
  9. import javax.net.ssl.SSLSession;
  10. import javax.net.ssl.X509TrustManager;
  11. import javax.security.cert.CertificateException;
  12.  
  13. /**
  14.  * Created by Edison_this on 15.07.2018.
  15.  */
  16.  
  17. public class MyTrustManager {
  18.  
  19.  
  20.  
  21.     public static void trustEveryone() {
  22.         try {
  23.             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
  24.                 public boolean verify(String hostname, SSLSession session) {
  25.                     return true;
  26.                 }});
  27.             SSLContext context = SSLContext.getInstance("TLS");
  28.             context.init(null, new X509TrustManager[]{new X509TrustManager(){
  29.                 public void checkClientTrusted(X509Certificate[] chain,
  30.                                                String authType) {}
  31.                 public void checkServerTrusted(X509Certificate[] chain,
  32.                                                String authType) {}
  33.                 public X509Certificate[] getAcceptedIssuers() {
  34.                     return new X509Certificate[0];
  35.                 }}}, new SecureRandom());
  36.             HttpsURLConnection.setDefaultSSLSocketFactory(
  37.                     context.getSocketFactory());
  38.         } catch (Exception e) { // should never happen
  39.             e.printStackTrace();
  40.         }
  41.     }
  42. }