首页 > 解决方案 > Apache HTTP 客户端:未捕获 NoHttpResponseException 异常?

问题描述

NoHttpResponseException如果被捕获,我想获取发送请求的重试总次数。我尝试使用 try-catch 块来实现该行为并且有一个奇怪的行为:

  1. 在我实现此行为之前,抛出异常并且程序中断。
  2. 我实现了这个行为后,不再抛出异常,程序正常运行。但是,该catch部分中的代码似乎并未真正执行:
        int retry = 0;
        final int MAX_RETRY = 1000;
        String response = null;
        JsonObject responseInJson = null;       
        while(true) {
            try {
                response = httpClient.execute(httpPost, responseHandler);
                break;
            } catch (IOException exception) {
                if(exception instanceof NoHttpResponseException) {
                    retry++;
                    System.out.println("Retry for the " +  retry + " time(s)");
                    if(retry == MAX_RETRY) {
                        throw exception;
                    }
                } else {
                    System.out.println("Another exception occured");
                    throw exception;
                }   
            } 
        }   

我的班级有一个属性: protected CloseableHttpClient httpClient;

属性在构造函数中初始化:

    public AbstractData() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(28800000)
                .setConnectTimeout(28800000)
                .setSocketTimeout(28800000)
                .build();
        this.httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setMaxConnPerRoute(4)
                .setMaxConnTotal(4)
                .build();
    }

我的问题是,我在 try-catch 块中实现行为的方式是否存在任何逻辑错误?并且有没有更好的方法来直接改变DefaultHttpRequestRetryHandler执行此行为(我试图查找并没有找到一个示例来检查发送请求的重试次数)。

标签: javaapache-httpcomponents

解决方案


推荐阅读