Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
Julian Avatar asked Dec 30 '25 09:12

Julian


1 Answers

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

HttpRequest request = HttpRequest.newBuilder()
                       .uri(URI.create("*URL*"))
                       .header("User-Agent", "Mozilla/5.0")
                       .build();
like image 131
Julian Avatar answered Dec 31 '25 22:12

Julian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!