Setup AsyncHttpClient to use HTTPS

前端 未结 3 736
一整个雨季
一整个雨季 2020-12-05 06:27

I am using com.loopj.android:android-async-http:1.4.9 for my request to server. It was working fine until I SSL/TLS is required in my server. So I need to modif

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 06:28

    I assume you have a self signed certificate on your server, I dont have a code that does it using com.loopj.android:android-async-http:1.4.9, but I can give you code that uses URLConnection and which loads crt file (my.server.net.crt) from assets folder.:

      public static HttpsURLConnection connectSelfSignedHttps(Context ctx, String surl) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    
        // Load CAs from an InputStream
        // (could be from a resource or ByteArrayInputStream or ...)
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
    
        // 
        InputStream caInput = new BufferedInputStream(ctx.getApplicationContext().getAssets().open("my.server.net.crt"));
        Certificate ca;
        try {
          ca = cf.generateCertificate(caInput);
          //System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
        } finally {
          caInput.close();
        }
    
        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    
        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);
    
        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);
    
        // Tell the URLConnection to use a SocketFactory from our SSLContext
        URL url = new URL(surl);
        HttpsURLConnection urlConnection =
            (HttpsURLConnection)url.openConnection();
        urlConnection.setSSLSocketFactory(context.getSocketFactory());
    
        return urlConnection;
      }
    

提交回复
热议问题