Simple java.net.http.HttpClient with and without basis authentication

Without authentication

private static String downloadWebPageContentSynchronously(String website) {
    try (HttpClient httpClient = newHttpClient()) {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(website))
                .build();

        try {
            HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
            if (response.statusCode() == 200) {
                byte[] responseBody = response.body();
                // website fetched 
                return new String(responseBody, StandardCharsets.UTF_8);
            }
        } catch (IOException | InterruptedException e) {
            return null;
        }
    }
    return null;
}

With authentication

private static String downloadWebPageContentSynchronously(String website) {
    try (HttpClient httpClient = HttpClient.newBuilder()
            .authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username", "password".toCharArray());
                }
            })
            .build()) {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(website))
                .build();

        try {
            HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
            if (response.statusCode() == 200) {
                byte[] responseBody = response.body();
                // website fetched 
                return new String(responseBody, StandardCharsets.UTF_8);
            }
        } catch (IOException | InterruptedException e) {
            return null;
        }
    }
    return null;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.