Java中CloseableHttpClient的超时设置和异常处理

Java开发我们常常需要和第三方系统进行通信,通信的方式有多种,如dubbo方式,webservice,微服务和CloseableHttpClient等方式,常涉及到超时问题,这里主要说的是CloseableHttpClient的超时设置以及超市了的异常处理;一般思路就是,

1,定义超时的时间,这个一般作为一个配置项,方便随时修改;

2,请求配置对象RequestConfig设置超时时间,然后设置到 HttpGet 或 HttpPost 请求方法对象;

3,使用CloseableHttpClient对象执行相应的请求方法,同时使用 try...catch... 捕获异常,对于超时可通过 SocketTimeoutExcetption 和 ConnectTimeoutException捕获异常;

例如下面简要例子(相应的jar自行网上查找);

package com.xxx.yyy.kkk;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.IOException;
import java.net.SocketTimeoutException;

public class HttpClient001 {
	
	public void getXXX() throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();	    
	    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
	            .setSocketTimeout(1000).setConnectTimeout(1000).build();
	    HttpGet httpGet = new HttpGet("http://www.xxx.com");
	    httpGet.setConfig(requestConfig);	    
	    try {	        
	        CloseableHttpResponse response = httpclient.execute(httpGet);
	        //....do more work...
	    } catch (SocketTimeoutExcetption | ConnectTimeoutException ex) {
	    	System.out.println("请求连接超时");	        
	    } catch (Exception ex) {
	    	System.out.println("请求异常,异常信息:" + ex.getMessage());	 
		}
	}

}

这样在Java后端向第三方请求时就可以自己设定需要的超时时间,比较可控点,怎么样,试一下吧...

 

展开阅读全文

没有更多推荐了,返回首页