做项目的时候需要使用到远程调用某个接口,采用简单的httpclient是一个不错的选择;采用http发送请求最核心的代码是httpClient.execute(httpPost)
下面是我项目中使用的工具类HttpClientUtil ,可以直接进行调用
/**
* httpclient util 处理http请求工具类
*
* @author administrator
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private final CloseableHttpClient httpClient;
private final RequestConfig requestConfig;
public HttpClientUtil(CloseableHttpClient httpClient, RequestConfig requestConfig) {
this.httpClient = httpClient;
this.requestConfig = requestConfig;
}
/**
* 处理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;
} finally {
try {
httpClient.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
return rpcResponse;
}
/**
* 处理post请求
*
* @param jsonObj
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
private HttpResponse doPost(JSONObject jsonObj, StringBuffer url)
throws IOException, ClientProtocolException {
HttpResponse response;
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 {
response = httpClient.execute(httpPost);
} finally {
httpPost.releaseConnection();
}
return response;
}
/**
* 处理get请求
*
* @param url
* @return
* @throws IOException
* @throws ClientProtocolException
*/
private HttpResponse doGet(StringBuffer url) throws IOException, ClientProtocolException {
HttpResponse response;
HttpGet httpGet = new HttpGet(url.toString());
httpGet.setConfig(this.requestConfig);
// do get
try {
response = httpClient.execute(httpGet);
} finally {
httpGet.releaseConnection();
}
return response;
}
/**
* 拼接url
*
* @param request
* @return
*/
private static StringBuffer disposeUrl(RpcRequest request) {
StringBuffer url = new StringBuffer();
if (!request.getGatewayAddress().startsWith("http")) {
url.append("http://");
}
url.append(request.getGatewayAddress() + "/services");
if (!request.getExecutorApiPath().startsWith("/")) {
url.append("/");
}
url.append(request.getExecutorApiPath());
return url;
}
}
写一个main函数进行调用
public static void main(String[] args) {
RpcRequest request = new RpcRequest();
JSONObject jsonObj = request.getParameters();
CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
.setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置超时时间
HttpClientUtil httpClientUtil = new HttpClientUtil(httpClient, requestConfig);
RpcResponse response = httpClientUtil.doWithRequest(request, jsonObj);
}