Αίτημα HTTP στη Java


import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class UrlRetriever {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: UrlRetriever URL");
            System.exit(1);
        }

        try {
            // Make an HTTP or HTTPS request with bounded connection and request times.
            var request = HttpRequest.newBuilder(URI.create(args[0]))
                .timeout(Duration.ofSeconds(30))
                .GET()
                .build();
            var client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();

            // Decode the response using its declared charset, defaulting to UTF-8.
            var response = client.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() >= 400) {
                System.err.println("HTTP error: " + response.statusCode());
                System.exit(1);
            }
            System.out.println(response.body());
        } catch (IllegalArgumentException e) {
            System.err.println("Invalid HTTP(S) URL: " + e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Request failed: " + e.getMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Request interrupted");
            System.exit(1);
        }
    }
}