`package com.haier.hsi.uap.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haier.hsi.uap.commons.RequestStatisticController;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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 java.io.IOException;
import java.util.Map;
/*
请求工具类
@author HanJianXiao
* @date 2017-07-11
*/<br />_//_RequestStatisticController为url切割 最下面附上代码
_public class RequestUtils {
_//日志<br /> _**private static **Logger _LOGGER _= LoggerFactory._getLogger_(RequestUtils.**class**);
_/**<br /> * post请求<br /> *<br /> * _**_@param __url _**_请求地址<br /> * _**_@param __json _**_请求参数<br /> * _**_@return _**_响应信息<br /> */<br /> _**public static **JSONObject postRequest(String url, JSONObject json) {<br /> StringEntity stringEntity = **new **StringEntity(json.toJSONString(), **"utf-8"**);<br /> JSONObject obj = **new **JSONObject();<br /> _// 创建http请求.<br /> _CloseableHttpClient httpclient = HttpClients._createDefault_();<br /> HttpPost httpPost = **new **HttpPost(url);<br /> httpPost.setHeader(**"Content-Type"**, **"application/json;charset=UTF-8"**);<br /> _// 设置发送数据<br /> _httpPost.setEntity(stringEntity);<br /> _// 创建响应<br /> _CloseableHttpResponse response = **null**;<br /> **try **{<br /> _// 执行请求<br /> _response = httpclient.execute(httpPost);<br /> _// 获取响应实体<br /> _HttpEntity entity = response.getEntity();<br /> **if **(entity != **null**) {<br /> String str = EntityUtils._toString_(entity);<br /> obj = JSONObject._parseObject_(str);<br /> System.**_out_**.println(**"--------------------------------------"**);<br /> System.**_err_**.println(**"url:" **+ url);<br /> System.**_err_**.println(**"stringEntity:" **+ stringEntity);<br /> System.**_err_**.println(**"响应状态" **+ response.getStatusLine());<br /> System.**_err_**.println(**"响应内容长度 : " **+ entity.getContentLength());<br /> System.**_err_**.println(**"响应内容 : " **+ str);<br /> System.**_out_**.println(**"--------------------------------------"**);<br /> }<br /> } **catch **(Exception e) {<br /> _LOGGER_.error(e.getMessage());<br /> obj.put(**"flag"**, **false**);<br /> obj.put(**"msg"**, e.getMessage());<br /> } **finally **{<br /> **try **{<br /> **if **(**null **!= response) {<br /> response.close();<br /> }<br /> } **catch **(IOException e) {<br /> _LOGGER_.error(e.getMessage());<br /> }<br /> **try **{<br /> **if **(**null **!= httpclient) {<br /> httpclient.close();<br /> }<br /> } **catch **(IOException e) {<br /> _LOGGER_.error(e.getMessage());<br /> }<br /> }<br /> **return **obj;<br /> }
**public static **JSONObject postRequestWithHeader(String url, JSONArray jsons, Map<String,String> map) {<br /> StringEntity stringEntity = **new **StringEntity(jsons.toJSONString(), **"utf-8"**);<br /> JSONObject obj = **new **JSONObject();<br /> _// 创建http请求.<br /> _CloseableHttpClient httpclient = HttpClients._createDefault_();<br /> HttpPost httpPost = **new **HttpPost(url);<br /> httpPost.setHeader(**"Content-Type"**, **"application/json;charset=UTF-8"**);<br /> **for**(Map.Entry<String, String> entry : map.entrySet()){<br /> String mapKey = entry.getKey();<br /> String mapValue = entry.getValue();<br /> httpPost.setHeader(mapKey, mapValue);<br /> }<br /> _// 设置发送数据<br /> _httpPost.setEntity(stringEntity);<br /> _// 创建响应<br /> _CloseableHttpResponse response = **null**;<br /> **try **{<br /> RequestStatisticController._incrSum_(url);<br /> StackTraceElement[] stackTrace = Thread._currentThread_().getStackTrace();<br /> StackTraceElement element = stackTrace[2];<br /> String classMethod = element.getClassName() + **"." **+ element.getMethodName();<br /> _LOGGER_.info(**"----- " **+ classMethod + **" 接口执行请求开始 -----"**);<br /> _LOGGER_.warn(**"----- 执行请求:" **+ url);<br /> **long **loggerStart = System._currentTimeMillis_();<br /> _// 执行请求<br /> _response = httpclient.execute(httpPost);<br /> _// 获取响应实体<br /> _HttpEntity entity = response.getEntity();<br /> **if **(**null **!= entity) {<br /> String str = EntityUtils._toString_(entity);<br /> obj = JSONObject._parseObject_(str);<br /> _LOGGER_.info(**"----- 响应实体解析开始 -----"**);<br /> _LOGGER_.warn(**"----- 响应状态:" **+ response.getStatusLine());<br /> _LOGGER_.warn(**"----- 内容长度:" **+ entity.getContentLength());<br /> _LOGGER_.warn(**"----- 响应内容:" **+ str);<br /> _LOGGER_.info(**"----- 响应实体解析结束 -----"**);<br /> }<br /> **long **loggerEnd = System._currentTimeMillis_();<br /> _LOGGER_.info(**"----- " **+ classMethod + **" 接口执行耗时:" **+ (loggerEnd - loggerStart) + **" ms -----"**);<br /> _LOGGER_.info(**"----- " **+ classMethod + **" 接口执行请求结束 -----"**);<br /> } **catch **(Exception e) {<br /> RequestStatisticController._incrFail_(url, e.getMessage());<br /> _LOGGER_.error(**"call url:{} failed."**, url);<br /> _LOGGER_.error(e.getMessage());<br /> obj.put(**"flag"**, **false**);<br /> obj.put(**"msg"**, e.getMessage());<br /> } **finally **{<br /> _closeResource_(httpclient, response);<br /> }<br /> **return **obj;<br /> }<br /> **private static void **closeResource(CloseableHttpClient httpclient, CloseableHttpResponse response) {<br /> **try **{<br /> **if **(**null **!= response) {<br /> response.close();<br /> }<br /> } **catch **(IOException e) {<br /> _LOGGER_.error(e.getMessage());<br /> }<br /> **try **{<br /> **if **(**null **!= httpclient) {<br /> httpclient.close();<br /> }<br /> } **catch **(IOException e) {<br /> _LOGGER_.error(e.getMessage());<br /> }<br /> }<br />}`
//RequestStatisticControlle 类
`package com.haier.hsi.uap.commons;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.StringUtils;
import org.jboss.netty.util.internal.ConcurrentHashMap;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class RequestStatisticController {
private final static ConcurrentHashMap
private final static ConcurrentHashMap
private final static String YYYY_MM_DD_HH_MM_SS = “yyyy-MM-dd HH:mm:ss”;
// @Autowired
// private IBaseRedisService
private static AtomicBoolean openStatitis = new AtomicBoolean(false);
private static AtomicInteger statsCnt = new AtomicInteger(5000);
**public static void **incrSum(String url) {<br /> **if **(!_openStatitis_.get()) {<br /> **return**;<br /> }
**if **(**_STATISTIC_**.size() > _statsCnt_.get()) {<br /> **return**;<br /> }
**if **(StringUtils._isEmpty_(url)) {<br /> **return**;<br /> }
**if **(url.contains(**"?"**)) {<br /> url = url.substring(0, url.lastIndexOf(**"?"**));<br /> }
**if **(url.contains(**"("**)) {<br /> url = url.substring(0, url.lastIndexOf(**"("**));<br /> }
**if **(!**_STATISTIC_**.containsKey(url)) {<br /> **_STATISTIC_**.put(url, **new **Counter());<br /> }
**_STATISTIC_**.get(url).setUrl(url).getSumCnt().incrementAndGet();<br /> }
**public static class **Counter {<br /> **private **String **url**;<br /> @JSONField(format = **"yyyy-MM-dd HH:mm:ss"**)<br /> @JsonFormat(<br /> pattern = **"yyyy-MM-dd HH:mm:ss"**,<br /> locale = **"zh"<br /> **)<br /> **private **Date **startDate **= **new **Date();
_/** Field description */<br /> _**public final **AtomicLong **sumCnt **= **new **AtomicLong();
_/** Field description */<br /> _**public final **AtomicLong **failCnt **= **new **AtomicLong();
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@return<br /> _**_*/<br /> _**public **String getUrl() {<br /> **return url**;<br /> }
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@param __url<br /> _**_*<br /> * _**_@return<br /> _**_*/<br /> _**public **Counter setUrl(String url) {<br /> **this**.**url **= url;
**return this**;<br /> }
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@return<br /> _**_*/<br /> _**public **Date getStartDate() {<br /> **return startDate**;<br /> }
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@param __startDate<br /> _**_*/<br /> _**public void **setStartDate(Date startDate) {<br /> **this**.**startDate **= startDate;<br /> }
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@return<br /> _**_*/<br /> _**public **AtomicLong getSumCnt() {<br /> **return sumCnt**;<br /> }
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@return<br /> _**_*/<br /> _**public **AtomicLong getFailCnt() {<br /> **return failCnt**;<br /> }
_/**<br /> * Method description<br /> *<br /> *<br /> * _**_@return<br /> _**_*/<br /> _@Override<br /> **public **String toString() {<br /> **final **StringBuffer sb = **new **StringBuffer(**"Counter{"**);
sb.append(**"url='"**).append(**url**).append(**'\''**);<br /> sb.append(**", startDate="**).append(**new **SimpleDateFormat(**_YYYY_MM_DD_HH_MM_SS_**).format(**startDate**));<br /> sb.append(**", sumCnt="**).append(**sumCnt**);<br /> sb.append(**", failCnt="**).append(**failCnt**);<br /> sb.append(**'}'**);
**return **sb.toString();<br /> }<br /> }
**public static void **incrFail(String url, String errMsg) {<br /> **if **(!_openStatitis_.get()) {<br /> **return**;<br /> }
**if **(**_STATISTIC_**.size() > _statsCnt_.get()) {<br /> **return**;<br /> }
**if **(StringUtils._isEmpty_(url)) {<br /> **return**;<br /> }
**if **(url.contains(**"?"**)) {<br /> url = url.substring(0, url.lastIndexOf(**"?"**));<br /> }
**if **(url.contains(**"("**)) {<br /> url = url.substring(0, url.lastIndexOf(**"("**));<br /> }
**if **(!**_STATISTIC_**.containsKey(url)) {<br /> **return**;<br /> }
**_STATISTIC_**.get(url).getFailCnt().incrementAndGet();
_// 记录错误信息<br /> _url = url.concat(**"@"**).concat(StringUtils._isNotEmpty_(errMsg)<br /> ? errMsg<br /> : **""**);
**if **(!**_ERR_STATISTIC_**.containsKey(url)) {<br /> **_ERR_STATISTIC_**.put(url, **new **Counter().setUrl(url));<br /> }
**_ERR_STATISTIC_**.get(url).getFailCnt().incrementAndGet();<br /> }<br />}<br />`