一.HttpClientUtil类,提供三个方法,分别是sendPostByForm,sendPostByJson,sendPostByXml
(1)sendPostByForm 处理 application/x-www-form-urlencoded格式报文的请求 (2)sendPostByJson 处理 application/json 格式报文的请求 (3)sendPostByXml 处理 text/xml 格式报文的请求 1.
package com.harara.fund.util.http;
import com.montnets.fund.constant.HttpConstant;
import com.montnets.fund.factory.LogFactory;
import com.montnets.fund.factory.service.LogService;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
private static LogService logger = LogFactory.getLogger();
public static String sendPostByJson(String url, String jsonParam,int reSend) {
String result = "";
long startTime=System.currentTimeMillis();
long endTime= 0L;
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = null;
try {
httpClient = HttpClientFactory.getInstance().getHttpClient();
HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
Header header=new BasicHeader("Accept-Encoding",null);
httpPost.setHeader(header);
StringEntity stringEntity = new StringEntity(jsonParam,HttpConstant.UTF8_ENCODE);
stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
logger.info("请求{}接口的参数为{}",url,jsonParam);
httpResponse = httpClient.execute(httpPost);
httpEntity= httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (Exception e) {
logger.error("请求{}接口出现异常",url,e);
if (reSend > 0) {
logger.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
result = sendPostByJson(url, jsonParam, reSend - 1);
if (result != null && !"".equals(result)) {
return result;
}
}
}finally {
try {
EntityUtils.consume(httpEntity);
} catch (IOException e) {
logger.error("http请求释放资源异常",e);
}
}
endTime=System.currentTimeMillis();
logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
return result;
}
public static String sendPostByForm(String url, Map<String,String> map,int reSend) {
String result = "";
long startTime=System.currentTimeMillis();
long endTime= 0L;
HttpEntity httpEntity = null;
UrlEncodedFormEntity entity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = null;
try {
httpClient = HttpClientFactory.getInstance().getHttpClient();
HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
entity = new UrlEncodedFormEntity(list,HttpConstant.UTF8_ENCODE);
httpPost.setEntity(entity);
logger.info("请求{}接口的参数为{}",url,map);
httpResponse = httpClient.execute(httpPost);
httpEntity= httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (Exception e) {
logger.error("请求{}接口出现异常",url,e);
if (reSend > 0) {
logger.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
result = sendPostByForm(url, map, reSend - 1);
if (result != null && !"".equals(result)) {
return result;
}
}
}finally {
try {
EntityUtils.consume(httpEntity);
} catch (IOException e) {
logger.error("http请求释放资源异常",e);
}
}
endTime=System.currentTimeMillis();
logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
return result;
}
public static String sendPostByXml(String url, String xmlParam,int reSend) {
String result = "";
long startTime = System.currentTimeMillis();
long endTime = 0L;
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = null;
try {
httpClient = HttpClientFactory.getInstance().getHttpClient();
HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
StringEntity stringEntity = new StringEntity(xmlParam, HttpConstant.UTF8_ENCODE);
stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
stringEntity.setContentType(HttpConstant.TEXT_XML);
httpPost.setEntity(stringEntity);
logger.info("请求{}接口的参数为{}", url, xmlParam);
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity,HttpConstant.UTF8_ENCODE);
} catch (Exception e) {
logger.error("请求{}接口出现异常", url, e);
if (reSend > 0) {
logger.info("请求{}出现异常:{},进行重发。进行第{}次重发", url, e.getMessage(), (HttpConstant.REQ_TIMES - reSend + 1));
result = sendPostByJson(url, xmlParam, reSend - 1);
if (result != null && !"".equals(result)) {
return result;
}
}
} finally {
try {
EntityUtils.consume(httpEntity);
} catch (IOException e) {
logger.error("http请求释放资源异常", e);
}
endTime = System.currentTimeMillis();
logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));
return result;
}
}
}
2.HttpClient工厂类HttpClientFactory,从工厂类获取HttpClient连接
package com.harara.fund.util.http;
import com.montnets.fund.constant.HttpConstant;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;
public class HttpClientFactory {
private static HttpClientFactory instance = null;
private HttpClientFactory()
{
}
public synchronized static HttpClientFactory getInstance()
{
if (instance == null)
{
instance = new HttpClientFactory();
}
return instance;
}
public synchronized HttpClient getHttpClient()
{
HttpClient httpClient = null;
if (HttpConstant.IS_KEEP_ALIVE)
{
httpClient = new KeepAliveHttpClientBuilder().getKeepAliveHttpClient();
} else
{
httpClient = new HttpClientBuilder().getHttpClient();
}
return httpClient;
}
public HttpPost httpPost(String httpUrl)
{
HttpPost httpPost = null;
httpPost = new HttpPost(httpUrl);
if (HttpConstant.IS_KEEP_ALIVE)
{
httpPost.setHeader("Connection", "Keep-Alive");
}
return httpPost;
}
private static class KeepAliveHttpClientBuilder{
private static HttpClient httpClient;
private synchronized HttpClient getKeepAliveHttpClient()
{
if (httpClient == null)
{
LayeredConnectionSocketFactory sslsf = null;
try {
sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create().register("https", sslsf)
.register("http", new PlainConnectionSocketFactory()).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(HttpConstant.MAX_TOTAL);
cm.setDefaultMaxPerRoute(HttpConstant.MAX_CONN_PER_ROUTE);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
.setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
}
return httpClient;
}
}
private static class HttpClientBuilder{
private HttpClient httpClient;
private synchronized HttpClient getHttpClient()
{
if(httpClient == null){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
.setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
}
return httpClient;
}
}
}
3.HttpClient请求常量类
package com.harara.fund.constant;
public class HttpConstant {
public static final int CONNECT_TIMEOUT = 3*1000;
public static final int SOCKET_TIMEOUT = 10*1000;
public static final int MAX_TOTAL = 10;
public static final int MAX_CONN_PER_ROUTE = 2;
public static final boolean IS_KEEP_ALIVE = true;
public static final int REQ_TIMES = 3;
public static final String UTF8_ENCODE = "UTF-8";
public static final String APPLICATION_JSON = "application/json";
public static final String TEXT_XML = "text/xml";
}
|