欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient HttpMethod 超时设置

程序员文章站 2022-04-24 18:49:17
...

今天碰到了个问题. HttpClient 和HttpMethod 都进行了超时设置.
url如果使用域名形式的话,超时设置是起作用的,但如果是IP形式的话,超时设置完全不起作用.

public static void main(String[] args) throws HttpException, IOException {
		
		int clientConn = 10;
		int clientSot  = 10;
		int methodSot  = 10;
		String url = "http://123.124.21.22";
		
		Long t1 = get();
		HttpClient shortClient = new HttpClient();
//		shortClient.getHttpConnectionManager().getParams().setConnectionTimeout(clientConn);
//		shortClient.getHttpConnectionManager().getParams().setSoTimeout(clientSot);
		MultiThreadedHttpConnectionManager m = new MultiThreadedHttpConnectionManager();
		m.getParams().setConnectionTimeout(1000);
		m.getParams().setSoTimeout(1000);
		shortClient.setHttpConnectionManager(m);
		Long t2 = get();
		System.out.println("Client inited : "+(t2-t1));
		
		HttpMethod method = new GetMethod(url);
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(0,false));
		method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, methodSot);
		Long t3 = get();
		System.out.println("Method inited : "+(t3-t2));
		int ret = 0;
		try{
			ret = shortClient.executeMethod(method);
		}catch(Exception e){
			e.printStackTrace();
		}
		Long t4 = get();
		System.out.println("Method executed : "+(t4-t3));
		
		if (ret == 200) {
			String content = method.getResponseBodyAsString();
			System.out.println(content);
		}
	}
	
	private static long get(){
		return new Date().getTime();
	}

 

可见,HttpClient使用MultiThreadedHttpConnectionManager 管理后,超时设置应该在MultiThreadedHttpConnectionManager 中设置, 原来HttpClient中的超时设置已经无效.之前碰到的20+秒的超时时间是由路由设置