好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java中HttpClient的错误处理

说明

1、HttpClient异步请求返回CompletableFuture,其自带的exceptionally方法可用于fallback处理。

2、HttpClient不像WebClient那样,它不会出现4xx或5xx的状态码异常,需要根据自己的情况进行处理,手动检测状态码异常或返回其他内容。

实例

    @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测试数据"))
                .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());
    }

以上就是java中HttpClient的错误处理,希望对大家有所帮助。 更多Java学习指路: Java基础

本教程操作环境:windows7系统、java10版,DELL G3电脑。

查看更多关于java中HttpClient的错误处理的详细内容...

  阅读:48次