I want to make a GET-request, which works fine with OkHttpClient, my webbrowsers and postman. But when I use the Java HTTP Client, I receive the Response Code 451. This is my code:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("*Some URL*"))
.build();
HttpResponse<String> response=null;
try {
response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}System.out.println(response.body());
"451" is what is printed. Why?
Adding the "User-Agent"-Header solved my problem.
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("*URL*"))
.header("User-Agent", "Mozilla/5.0")
.build();