天天看點

HttpClient如何自定義重試方法

問題:

在寫項目的時候,使用到 org.apache.commons.httpclient.HttpClient ,進行http請求,發現有時一些連結無法正常連接配接,這時候就會自動重連3次,導緻一個http連接配接的時間過長。

解決方法:

設定連接配接逾時時間、設定自動重連方法,防止http連接配接時間過長。

思路:

開始以為是沒有設定連接配接逾時導緻的,後來發現設定了逾時還是會重連,于是查找到GetMethod的 setMethodRetryHandler 方法,通過這個方法來設定自己的重連函數,但是發現這個方法已經過時了,官方推薦使用 HttpMethodParams 的方式來設定重連函數。

public static HttpClient getHttpClient() {
        HttpClient client = new HttpClient();
        // 設定連接配接逾時時間
        client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
        return client;
    }      
public static BufferedImage getPicture1(Camera camera) {
        GetMethod method = new GetMethod(getURL(camera.getId()));
        method.setDoAuthentication(true);
        // 連接配接失敗後,禁止重連
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                (HttpMethodRetryHandler) (method1, exception, executionCount) -> false);
 
        try {
            int statusCode = getHttpClient().executeMethod(method);
 
            try (InputStream in = method.getResponseBodyAsStream()) {
                return ImageIO.read(in);
            }
        } catch (IOException e) {
            return null;
        } finally {
            method.releaseConnection();
        }
    }      
// 設定重連次數為10次
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(10,false));