标签:sage print 方法 col time java methods connect tom
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());
}
}
标签:sage print 方法 col time java methods connect tom
原文地址:https://www.cnblogs.com/muxi0407/p/11589498.html