Home >Java >javaTutorial >Analysis of error handling examples of HttpClient in Java

Analysis of error handling examples of HttpClient in Java

王林
王林forward
2023-05-08 11:07:071045browse

Explanation

1. HttpClient asynchronous request returns CompletableFuture, and its own exceptionally method can be used for fallback processing.

2. Unlike WebClient, HttpClient does not have 4xx or 5xx status code exceptions. You need to handle it according to your own situation, manually detect status code exceptions or return other content.

Example

    @Test
    public void testHandleException() throws ExecutionException, InterruptedException {
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(5000))
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://twitter.com"))
                .build();
 
        CompletableFuture<String> result = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
//                .whenComplete((resp,err) -> {
//                    if(err != null){
//                        err.printStackTrace();
//                    }else{
//                        System.out.println(resp.body());
//                        System.out.println(resp.statusCode());
//                    }
//                })
                .thenApply(HttpResponse::body)
                .exceptionally(err -> {
                    err.printStackTrace();
                    return "fallback";
                });
        System.out.println(result.get());
    }

The above is the detailed content of Analysis of error handling examples of HttpClient in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete