package com.paic.padlife.common; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; 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.methods.HttpUriRequest; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.paic.padlife.biz.product.common.utils.PrintLog; /** * @author ex-chenkefeng001 * HttpClient工具类 */ public class PafaHttpClient { private static final Logger logger = LoggerFactory.getLogger(PafaHttpClient.class); private static PafaHttpManager manager; /** * 发送GET请求 * * @param url * 请求地址 * @param callback * 请求结束之后回调 * @param params * 请求参数 */ public static <T, K, V> void doGet(String url, ParamDTO<K, V> params, InvokeHandleCallback<T> callback) { // 获取httpGet PrintLog.info(logger, "[{}] doGet start... and params is [{}]", url, params); HttpGet get; if(params != null && params.isNotEmpty()){ get = new HttpGet(String.format("%s?%s", url, params.toUrlParams("utf-8"))); }else{ get = new HttpGet(url); } processAndExecuteRequest(get,callback); } /** * 发送GET请求 * * @param url * 请求地址 * @param callback * 请求结束之后回调 */ public static <T> void doGet(String url, InvokeHandleCallback<T> callback) { doGet(url, null, callback); } /** * 发送POST请求 * * @param url * 请求地址 * @param params * 请求参数 * @param callback * 请求结束之后回调 */ public static <T, K, V> void doPost(String url, ParamDTO<K, V> params, InvokeHandleCallback<T> callback) { PrintLog.info(logger, "[{}] doPost start... and params is [{}]", url, params); HttpPost post = new HttpPost(url); List<BasicNameValuePair> list = null; if(params != null){ list = params.preparePostData(); } try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list); post.setEntity(entity); processAndExecuteRequest(post, callback); } catch (UnsupportedEncodingException e) { PrintLog.info(logger, "UrlEncodedFormEntity..init error...", e); if(callback != null){ callback.onError(e); } } } /** * 发送POST请求 * * @param url * 请求地址 * @param body * 请求体 * @param callback * 请求结束之后回调 */ public static <T> void doPost(String url, String body, InvokeHandleCallback<T> callback) { PrintLog.info(logger, "[{}] doPost start... and params is [{}]", url, body); HttpPost post = new HttpPost(url); if(body != null){ try { post.setEntity(new StringEntity(body, "utf-8")); } catch (UnsupportedEncodingException e) { PrintLog.info(logger, "UrlEncodedFormEntity..init error...", e); if(callback != null){ callback.onError(e); } } } processAndExecuteRequest(post, callback); } @SuppressWarnings("unchecked") private static <T> void processAndExecuteRequest(HttpUriRequest req,InvokeHandleCallback<T> callback){ if(manager == null){ manager = PafaHttpManager.getDefault(); } PrintLog.info(logger, "pool manager available client number is <池中活动的client数目> [{}]," + "leased number is <池中针对该地址连接的最大连接数目> [{}]," + "pending number is <当前正在等待的连接数> [{}]," + "max allow number <服务器允许最大的并发client数 > is [{}]", manager.getAvailable(),manager.getLeased(),manager.getPending(),manager.getMax()); CloseableHttpClient httpClient = manager.getHttpClient(); CloseableHttpResponse httpResp = null; HttpEntity entity = null; try { httpResp = httpClient.execute(req); StatusLine statusLine = httpResp.getStatusLine(); if(statusLine.getStatusCode() == 200){ entity = httpResp.getEntity(); String respDat a= EntityUtils.toString(entity, "utf-8"); PrintLog.info(logger, "remote server response dat ais [{}]", respData); if(callback != null){ callback.onSuccess(JSON.parseObject(respData, (Class<T>)callback.getClazz())); } }else{ PrintLog.info(logger, "remote server response code is [{}]..", statusLine.getStatusCode()); if(callback != null){ callback.onRemoteError(statusLine); } } } catch (ClientProtocolException e) { //e.printStackTrace(); PrintLog.info(logger, "", e); if(callback != null){ callback.onError(e); } } catch (IOException e) { if(e instanceof ConnectionPoolTimeoutException){ }else{ PrintLog.info(logger, "", e); ///e.printStackTrace(); } if(callback != null){ callback.onError(e); } } finally { try { if(entity != null){ entity.getContent().close(); } if (httpResp != null) { httpResp.close(); } //httpClient.close(); } catch (Exception e2) { // do not handle.. } } } /** * @author ex-chenkefeng001 * 请求结果回调处理 * @param <T> */ public abstract static class InvokeHandleCallback<T> { /** * 发生错误时回调,例如:超时等 * * @param e */ public void onError(Exception e) { manager.release(); } /** * 远程服务器错误 * * @param e */ public void onRemoteError(StatusLine status) { manager.release(); } public void onSuccess(T resp){ manager.release(); }; @SuppressWarnings("unchecked") public Class<?> getClazz() { Type type = this.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Type[] types = ptype.getActualTypeArguments(); if (types.length > 0) { return (Class<T>) types[0]; } } return Object.class; } } public static void main(String[] args) { for(;;){ new Thread(){ public void run() { doGet("http://localhost:7001/padlife/do/product/queryAllAddress?productId=1", new InvokeHandleCallback<String>() { @Override public void onSuccess(String resp) { super.onSuccess(resp); //System.out.println(resp); } public void onError(Exception e) { System.out.println(e.getMessage()); }; }); }; @Override protected void finalize() throws Throwable { super.finalize(); System.out.println("thread 对象销毁啦。。。"); } }.start(); try { TimeUnit.MILLISECONDS.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } } |
|