Search code examples
androidweb-servicessslandroid-ksoap2

How to connect an SSL enabled asmx web service with android


i'm trying to connect an asmx web service which has SSL enabled certificate from symantec. The web service works fine in browser with green indication. But unable to connect the webservice with android using ksoap library. I have added the public key of certificate(.cer file) in the aseets folder and added it to the trustmanager.


Solution

  • Here is the complete solution for how to handle SSL over android and c# webservice by using ksoap.

    1. customise your org.ksoap2.transport.org.ksoap2.transport class constructor like this

    public HttpTransportSE(Certificate ca, String url) {
        super(ca, url);
    }
    

    2. change some codes in org.ksoap2.transport.ServiceConnectionSE class

    public ServiceConnectionSE(Certificate ca, String url) throws IOException
    {
    
        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore;
        SSLContext context = null;
        try {
            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
            context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);
    
    
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    
        // Tell the URLConnection to use a SocketFactory from our SSLContext
    
    
        connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setSSLSocketFactory(context.getSocketFactory());
    
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
    }
    

    1. And send your Certificate ca

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    AssetManager assetManager = getAssets();
    InputStream caInput = new BufferedInputStream(assetManager.open("your_cert.cer"));
    Certificate ca = cf.generateCertificate(caInput);
    
    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(ca, url);