HttpClient如何自定义重试方法

问题:
在写项目的时候,使用到 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));

猜你喜欢

转载自blog.csdn.net/weixin_40816738/article/details/125918509
今日推荐