您的位置:首页 > 理论基础 > 计算机网络

单例模式使用httpclient发送请求

2018-03-01 17:10 190 查看
使用httpclient发送post和get请求时,需要实例化HttpClient实例,再调用httpClient.execute()方法,每次实例化HttpClient耗时较大,而且HttpClient实例不能共用,不利于大量的请求处理,考虑到HttpClient实例公用,可以采用单利模式进行处理。HttpClientUtil是处理http请求工具类,在这个工具类里面封装了post和get请求的处理逻辑public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

private CloseableHttpClient httpClient = null;
private RequestConfig requestConfig = null;

private static final HttpClientUtil HTTP_CLIENTUTIL = new HttpClientUtil();

/**
* 私有构造函数,禁止在外面new一个实例对象
* 初始化httpClient实例和requestConfig配置信息
*/
private HttpClientUtil() {
httpClient = HttpClients.custom().disableAutomaticRetries().build();;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
.setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置超时时间
}

/**
* 对外暴露获取实例的接口
* @return
*/
public synchronized static HttpClientUtil getInstance() {
return HTTP_CLIENTUTIL;
}

上面的代码通过单利模式生成HttpClientUtil实例,并且初始化Httpclient
紧接着开始处理post和get请求:/**
* 处理request请求
*
* @param request
* @param jsonObj
* @return
* @throws Exception
*/
public RpcResponse doWithRequest(RpcRequest request, JSONObject jsonObj) throws Exception {
RpcResponse rpcResponse = new RpcResponse();
rpcResponse.setRequestId(request.getRequestId());
StringBuffer url = disposeUrl(request);

try {

HttpResponse response = null;

if (request.getExecutorApiType().equalsIgnoreCase("GET")) {
response = doGet(url);

} else if (request.getExecutorApiType().equalsIgnoreCase("POST")) {
response = doPost(jsonObj, url);
}
if (null != response) {
StatusLine statusLine = response.getStatusLine();
rpcResponse.setCode(statusLine.getStatusCode());
rpcResponse.setResult(statusLine.toString() + ";请求路径:" + url.toString());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
return rpcResponse;
}

/**
* 处理post请求
*
* @param jsonObj
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
private HttpResponse doPost(JSONObject jsonObj, StringBuffer url)
throws IOException, ClientProtocolException {
HttpPost httpPost = new HttpPost(url.toString());
httpPost.setConfig(this.requestConfig);

// 构建消息实体
if (jsonObj != null) {
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
// do post
try(CloseableHttpResponse response = httpClient.execute(httpPost)){
return response;
} finally {
httpPost.releaseConnection();
}
}

/**
* 处理get请求
*
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
private HttpResponse doGet(StringBuffer url) throws IOException, ClientProtocolException {
HttpGet httpGet = new HttpGet(url.toString());
httpGet.setConfig(this.requestConfig);
httpGet.addHeader("token", "testToken");
// do get
try(CloseableHttpResponse response = httpClient.execute(httpGet)){
return response;
} finally {
httpGet.releaseConnection();
}
}

/**
* 拼接url
*
* @param request
* @return
*/
private static StringBuffer disposeUrl(RpcRequest request) {
StringBuffer url = new StringBuffer();
//api路径以http开头,不走网关直接使用该路径
//否则请求需要走网关转发
if (!request.getExecutorApiPath().toLowerCase().startsWith("http")) {
if (!request.getGatewayAddress().toLowerCase().startsWith("http")) {
url.append("http://");
}
url.append(request.getGatewayAddress() + "/services");

if (!request.getExecutorApiPath().startsWith("/")) {
url.append("/");
}
}
url.append(request.getExecutorApiPath());

return url;
}外部调用方式: public static void main(String[] args) {

RpcRequest request = new RpcRequest();
String jsonMessage = "{\"key\":\"语文\",\"value\":\"78\"}";
JSONObject myJson = (JSONObject) JSON.parse(jsonMessage);

HttpClientUtil httpClientUtil = HttpClientUtil.getInstance();
RpcResponse response = httpClientUtil.doWithRequest(request, myJson);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单例模式 httpclient