DEV Community

GAURAV KUMAR
GAURAV KUMAR

Posted on

Get URL pointed Resource Information in Java

In this post we are going to know how to make HTTP requests in java. We'll see two ways - 1. Before Java 11 and 2. After Java 11.

Let us first see how we could make HTTP requests before Java 11. Here we are going to retrieve various metadata information of a file pointed by and URL.

package org.gaurav;

import java.io.IOException;
import java.net.*;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String url1 = "https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/salesforce_useful_validation_formulas.pdf";
        String url2 = "https://fastly.picsum.photos/id/112/600/600.jpg?hmac=hakYJ0LrbvOQ1fnbvBGE1ThGxufcyCWKNAfXrctqyWQ";
        String url3 = "https://picsum.photos/200/300";

        System.out.println("First URL Information");
        printHeaders(url1);

        System.out.println();
        System.out.println("Second URL Information");
        printHeaders(url2);

        System.out.println();
        System.out.println("Third URL Information");
        printHeaders(url3);
    }

    public static void printHeaders(String fileUrl) {
        try {
            URL url = new URI(fileUrl).toURL();
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Map<String, List<String>> headers = connection.getHeaderFields();

            for (Map.Entry<String, java.util.List<String>> entry : headers.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }

            connection.disconnect();
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the above code to see the output.

Now, let us see how we can do the same thing using Http Client API introduced in Java 11.

package org.gaurav;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String url1 = "https://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/salesforce_useful_validation_formulas.pdf";
        String url2 = "https://fastly.picsum.photos/id/112/600/600.jpg?hmac=hakYJ0LrbvOQ1fnbvBGE1ThGxufcyCWKNAfXrctqyWQ";
        String url3 = "https://picsum.photos/200/300";

        System.out.println("First URL Information");
        printHeaders(url1);

        System.out.println();
        System.out.println("Second URL Information");
        printHeaders(url2);

        System.out.println();
        System.out.println("Third URL Information");
        printHeaders(url3);
    }

    public static void printHeaders(String fileUrl) {
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fileUrl))
                .build();

        try {
            HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
            Map<String, List<String>> headers = response.headers().map();
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now let us discuss some reasons why should we use the newer one?

Here are a few reasons why these newer alternatives are preferred:

  1. Flexibility and Ease of Use: Libraries like Apache HttpClient and java.net.http.HttpClient provide more intuitive APIs for making HTTP requests and handling responses. They offer higher-level abstractions and better support for modern HTTP features.

  2. Performance: The newer libraries are designed with modern performance considerations in mind, including better connection pooling and asynchronous capabilities.

  3. Standardization: The java.net.http.HttpClient is part of the Java SE platform starting from Java 11, which means it's a standardized part of the Java ecosystem.

  4. Functional Programming: The new libraries often leverage functional programming features to provide more concise and expressive code when dealing with asynchronous operations.

Note: While HttpURLConnection can still be used for basic scenarios, newer libraries like Apache HttpClient and java.net.http.HttpClient offer better performance, improved features, and a more intuitive API for making HTTP requests and working with responses. It's a good idea to consider these alternatives when working with HTTP in modern Java applications.

Top comments (0)