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

Analysis of error handling examples of HttpClient in Java

王林
Release: 2023-05-08 11:07:07
forward
1076 people have browsed it

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());
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template