简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM