php网站 缓存,北镇网站建设,西安关键词排名推广,网站框架类型问题#xff1a; 在写项目的时候#xff0c;使用到 org.apache.commons.httpclient.HttpClient #xff0c;进行http请求#xff0c;发现有时一些链接无法正常连接#xff0c;这时候就会自动重连3次#xff0c;导致一个http连接的时间过长。
解决方法#xff1a; 设置连…问题 在写项目的时候使用到 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));