7: HTTPS Secure Connections

Making secure requests via HTTPS will work simply by making use of the java.net.URLConnection built-in support for HTTPS. This is implemented using the Java Secure Socket Extension, which provides more detail.

In summary though, there are two cases: server certificate only, and server + client certificate.

Server Certificate Only

This is simply achieved for all https URLs automatically, provided the security keys and hostname verification are handled correctly. More information on these details is in the Java API for HttpsURLConnection.

object Example7a extends App {
  val url = "https://www.amazon.co.uk/"
  val httpClient = new HttpClient
  val response = httpClient.get(url)

SSL Special Cases

You may possibly need to provide your own specific implementation for HostnameVerifier and even SSLSocketFactory. Config has hostnameVerifier and sslSocketFactory parameters to control these two configurable items on HttpsUrlConnections. Just create a Config instance with suitable values for these parameters and use it in your HttpClient.

Because your app can support multiple instances of Config at the same time, this allows different SSL connections to have their own parameters (i.e. each different HttpClient instance can have the particular Config necessary).

Insecure SSL

During development, or for other special cases, SSL can be used in an insecure way. Suppose, for example, my local development server has a self-signed certificate and I want to make LAN connections to it, so I might need to disable the normal safety checks. Config has a convenient method allowInsecureSSL to turn this feature on.

object Example7b extends App {
  val config = Config().allowInsecureSSL
  val url = "https://localhost/bee-client/test-echo-back.php"
  val httpClient = new HttpClient(config)
  val response = httpClient.get(url)

This is rather like curl -k. What it actually does is install a dumb HostnameVerifier and, via a dumb X509TrustManager, a neutered SSLSocketFactory.

Client & Server Certificate

Providing a client certificate is slightly more involved. Again, the standard Java APIs provide for this. See Java Secure Socket Extension for further details.