Search code examples
javahttphttp-response-codesjava-http-client

Why do I get HTTP Response Status Code 451 only when using the Java HTTP Client?


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?


Solution

  • Adding the "User-Agent"-Header solved my problem.

    HttpRequest request = HttpRequest.newBuilder()
                           .uri(URI.create("*URL*"))
                           .header("User-Agent", "Mozilla/5.0")
                           .build();