Android: HTTPS (SSL) connection using HttpsURLConnection

前端 未结 3 1235
醉梦人生
醉梦人生 2020-12-12 23:09

I have 2 apps, one is a Servlet/Tomcat Server, and the other is an Android app.

I want to use HttpURLConnection to send and receive XML between both.

Code:

相关标签:
3条回答
  • 2020-12-12 23:30

    You need to create a trust store file for your self-signed certificate as described here. Use it on the client side to connect with your server. It doesn't really matter if you use JKS or another format, I'll assume JKS for now.

    To accomplish what you have in mind you need a different TrustManager, obviously. You can use TrustManagerFactory and feed its trust settings with your newly created trust store.

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream("<path to your key store>");
    ks.load(in, "password".toCharArray());
    in.close();
    tmf.init(ks);
    TrustManager[] tms = tmf.getTrustManagers();
    

    Use tms to init your SSLContextinstead for the new trust settings to be used for your SSL/TLS connection.

    Also you should make sure that the CN part of the server TLS certificate is equal to the FQDN (fully qualified domain name) of your server, e.g. if your server base URL is 'https://www.example.com', then the CN of the certificate should be 'www.example.com'. This is needed for host name verification, a feature that prevents man-in-the-middle-attacks. You could disable this, but only when using this your connection will be really secure.

    0 讨论(0)
  • 2020-12-12 23:41

    If you want to ignore all the certificate, ignore the handshake, then this works: HttpsURLConnection and intermittent connections

    0 讨论(0)
  • 2020-12-12 23:46

    Create your trust store, store at as an asset and use it initialize this SocketFactory. Then use the factory instead of your own 'trust everybody' one.

    0 讨论(0)
提交回复
热议问题