A Java HTTPS client example

Java HTTPS client FAQ: Can you share some source code for a Java HTTPS client application?

Solution

Sure, here’s the source code for an example Java HTTPS client program I just used to download the contents of an HTTPS (SSL) URL. I actually found some of this code in a newsgroup a while ago, but I can’t find the source today to give them credit, so my apologies for that.

I just used this program to troubleshoot a problem with Java and HTTPS URLs, including all that nice Java SSL keystore and cacerts stuff you may run into when working with Java, HTTPS/SSL, and hitting a URL.

I’ve found through experience that this Java program should work if you are hitting an HTTPS URL that has a valid SSL certificate from someone like Verisign or Thawte, but will not work with other SSL certificates unless you go down the Java keystore road.

Example Java HTTPS client program

Here’s the source code for my simple Java HTTPS client program:

package foo;

import java.net.URL;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;

public class JavaHttpsExample
{

    public static void main(String[] args) throws Exception {
        String httpsURL = "https://your.https.url.here/";
        URL myUrl = new URL(httpsURL);
        HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        String inputLine;

        while ((inputLine = br.readLine()) != null) {
            System.out.println(inputLine);
        }

        br.close();
    }

}

Just change the URL shown there to the HTTPS URL you want to access, and hopefully everything will work well for you.

A Scala HTTPS example

While I’m in the neighborhood, here’s a Scala HTTPS translation of that Java code:

package https

import java.net.URL
import java.io.*
import javax.net.ssl.HttpsURLConnection

// note that this can throw an exception
@main def HttpsExample1(): Unit =

    val httpsURL = "https://alvinalexander.com"
    val myUrl: URL = URL(httpsURL)
    val conn: HttpsURLConnection = myUrl.openConnection().asInstanceOf[HttpsURLConnection]
    val is: InputStream = conn.getInputStream()
    val isr: InputStreamReader = InputStreamReader(is)
    val br: BufferedReader = BufferedReader(isr)

    var line = ""
    while ({line = br.readLine; line != null}) {
        println(line)
    }
    br.close()

Note that while this works, there are probably better ways to do this. I just tried to translate that Java Https example to a Scala Https example, so this is more or less a line-for-line translation.