http/https connections in Java

You have three choices for working with http or https in Java.

1. You can can use the HttpUrlConnection class. It supports only HTTP/1.1 protocol. This means that we can send only one request per TCP connection. Also HttpUrlConnection works only in synchronous mode. This means you must explicitly execute request in background thread if necessary, for example, for android platform.

The HttpsUrlConnection class handles the https request. If you don't need https specific functionality, you can work with hppts request via HttpUrlConnection. Both classes are implementations of the UrlConnection interface.

2. Java 9 introduces new http client and in Java 11 it was standardized. It supports both HTTP/1.1 and HTTP/2.0. Also it works in both synchronous and asynchronous mode.

3. Use any popular library like OkHttp:

  • supports HTTP/2, all requests to the same host share the same socket
  • transparent GZIP shrinks download sizes
  • response caching avoids the network completely for repeat requests
  • works in both synchronous and asynchronous mode
  • works on Android 5.0+ (API level 21+) and on Java 8+

Below example of reading text from url in synchronous mode.

Code example
String readText(String argUrl) throws IOException {
    URL url = new URL(argUrl);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // set some connection parameters
    conn.setConnectTimeout(5000);
    conn.setInstanceFollowRedirects(true);

    // set some http headers
    conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
    conn.addRequestProperty("User-Agent", "Mozilla...");
       
    try {
        int responseCode = conn.getResponseCode();

        // handle redirection
        if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
            conn = redirect(conn);
        } else if (responseCode >= 200 && responseCode < 300) {
            // read response as text
            try (BufferedReader reader = new BufferedReader(
                      new InputStreamReader(conn.getInputStream()))) {
                StringBuilder sb = new StringBuilder();
                String line = reader.readLine();

                while (line != null) {
                    // todo add progress listener if necessary
                    sb.append(line);
                    line = reader.readLine();
                }

                return sb.toString();
             } catch (Exception e) {
                e.printStackTrace();
             }
        } else handleError(conn);
    } finally {
        conn.disconnect(); // can be omitted if keep-alive supported
    }

    return null;
}
// import jdk.incubator.http.* // Java 9
// Java 11
java.net.http.*
// ...

String readText(String argUrl){
    HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(5))
        .followRedirects(SECURE)
        .build();
    
    HttpRequest request = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create(argUrl))
        .header("Accept-Language", "en-US,en;q=0.8")
        .header("User-Agent", "Mozilla...")
        .build();   
      
    HttpResponse<String> response = client.send(
        request,
        BodyHandlers.ofString());

    String responseBody = response.body();
    return responseBody;
}
OkHttpClient client = new OkHttpClient();

String readText(String argUrl){
    try{
        Request request = new Request.Builder()
           .url(argUrl)
           .addHeader("Accept-Language", "en-US,en;q=0.8")
           .addHeader("User-Agent", "Mozilla...")
           .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }catch(Exception e){
        return null
    }
}