/** *@Title: HttpClientBean.java *@Package com.nis.util.httpclient *@Description TODO *@author dell *@date 2016年11月7日 下午2:36:26 *@version 版本号 */ package com.nis.util.httpclient; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.springframework.web.servlet.support.RequestContext; import com.nis.exceptions.MaatConvertException; /** * @ClassName: HttpClientBean.java * @Description: TODO * @author (dell) * @date 2016年11月7日 下午2:36:26 * @version V1.0 */ public class HttpClientUtil { protected static Logger logger = Logger.getLogger(HttpClientUtil.class); /** * 处理get请求. * @param url 请求路径 * @return json * @throws IOException * @throws ClientProtocolException */ public static String get(String url) throws ClientProtocolException, IOException{ //实例化httpclient CloseableHttpClient httpclient = HttpClients.createDefault(); //实例化get方法 HttpGet httpget = new HttpGet(url); //请求结果 CloseableHttpResponse response = null; String content =""; // try { //执行get方法 response = httpclient.execute(httpget); // if(response.getStatusLine().getStatusCode()==200){ content = EntityUtils.toString(response.getEntity(),"utf-8"); // } // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } return content; } /** * 处理post请求. * @param url 请求路径 * @param params 参数 * @return json * @throws IOException * @throws ClientProtocolException */ public String post(String url,Map params) throws ClientProtocolException, IOException{ //实例化httpClient CloseableHttpClient httpclient = HttpClients.createDefault(); //实例化post方法 HttpPost httpPost = new HttpPost(url); //处理参数 List nvps = new ArrayList (); Set keySet = params.keySet(); for(String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } //结果 CloseableHttpResponse response = null; String content=""; // try { //提交的参数 UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8"); //将参数给post方法 httpPost.setEntity(uefEntity); //执行post方法 response = httpclient.execute(httpPost); // if(response.getStatusLine().getStatusCode()==200){ content = EntityUtils.toString(response.getEntity(),"utf-8"); // System.out.println(content); // } // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } return content; } /** * http get 获取消息 * @param destUrl 业务地址 * @param params 参数列表 * @return 查询结果数据json */ public static String getMsg(String destUrl, Map params, HttpServletRequest req) { RequestContext requestContext = new RequestContext(req); CloseableHttpResponse response = null; String result = null; try { URIBuilder uriBuilder = new URIBuilder(destUrl); for (String param : params.keySet()) { uriBuilder.addParameter(param, params.get(param).toString()); } HttpGet request = new HttpGet(uriBuilder.build()); request.setConfig(requestConfig); URI uri = request.getURI(); logger.info(uri); System.err.println(uri); response = getHttpClient().execute(request); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { result = EntityUtils.toString(response.getEntity()); logger.debug("获取消息成功,相应内容如下: " + result); } else { throw new MaatConvertException(requestContext.getMessage("request_service_failed") + ":" + status); } } catch (SocketTimeoutException e) { logger.error("获取消息失败 ", e); throw new MaatConvertException(requestContext.getMessage("request_service_failed") + ":timeout"); } catch (MaatConvertException e) { throw e; } catch (ConnectTimeoutException e) { logger.error("获取消息失败 ", e); throw new MaatConvertException(requestContext.getMessage("request_service_failed") + ":timeout"); } catch (Exception e) { logger.error("获取消息失败 ", e); throw new MaatConvertException(requestContext.getMessage("request_service_failed")); } finally { try { if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; } private static CloseableHttpClient httpClient = null; private static RequestConfig requestConfig; public static final int HTTP_SOCKET_TIMEOUT= 30000; public static final int HTTP_CONNECT_TIMEOUT= 10000; public static final int HTTP_CONNECT_REQUEST_TIMEOUT = 50000; public static final int HTTP_CONNECT_RETRY_TIMES = 3; //http 连接池 public static CloseableHttpClient getHttpClient() { if (httpClient == null) { //http 连接池管理 需后续实现 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); // 将最大连接数增加到200 cm.setMaxTotal(200); // 将每个路由基础的连接增加到20 cm.setDefaultMaxPerRoute(20); requestConfig = RequestConfig.custom() .setSocketTimeout( HTTP_SOCKET_TIMEOUT) .setConnectTimeout( HTTP_CONNECT_TIMEOUT) .setConnectionRequestTimeout( HTTP_CONNECT_REQUEST_TIMEOUT) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler( HTTP_CONNECT_RETRY_TIMES, false)) .build(); } return httpClient; } public static void main(String[] args) throws ClientProtocolException, IOException { HttpClientUtil hd = new HttpClientUtil(); hd.get("http://10.0.6.115:9200/_sql?sql=select * from dfipportlog-2016-09-07-15 limit 1 10"); Map map = new HashMap(); map.put("id","1"); hd.post("http://localhost:8080/springMVC/menu/getChildren.do",map); } }