1、Java开发我们常常需要和第三方系统进行通信,通信的方式有多种,如
(1)dubbo
(2)webservice
(3)微服务
(4)CloseableHttpClient等
2、以CloseableHttpClient为例 设置思路
首先请求配置对象RequestConfig设置超时时间
然后设置到 HttpGet 或 HttpPost 请求方法对象
3、以CloseableHttpClient为例
package com.gbm.common.util;
import org.apache.http.HttpEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
public static String HttpGet(String Url, String token){
String result=null;
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse newresponse = null;
try{
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(120000)
.setSocketTimeout(120000).setConnectTimeout(120000).build(); //设置2分钟超时
HttpGet httpget = new HttpGet(Url);
httpget.setConfig(requestConfig);
httpget.setHeader("token-Authorization", token);
try{
newresponse = httpclient.execute(httpget);
HttpEntity entity = newresponse.getEntity();
result = EntityUtils.toString(entity);
}finally{
newresponse.close();
}
}catch(Exception e){
logger.error("请求url:" + Url + "异常,异常信息:" + e.getMessage());
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
logger.error("关闭CloseableHttpClient异常,异常信息:" + e.getMessage());
}
}
return result;
}
}