日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

HttpClient如何自定義重試方法

作者:gblfy 更新時間: 2022-07-22 編程語言

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

解決方法:
設置連接超時時間、設置自動重連方法,防止http連接時間過長。

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

貼代碼,示例:使用httpClient進行http連接,獲取圖片。

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

這里我直接返回false,相當于關閉了重連,如果需要自定義重連次數,則需要這樣寫:

// 設置重連次數為10次
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(10,false));

原文鏈接:https://blog.csdn.net/weixin_40816738/article/details/125918509

欄目分類
最近更新