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;
}