• java模板模式项目中使用--封装一个http请求工具类


    需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑。

    模板:

    package com.crb.ocms.fund.domain.util.http;
    
    import com.alibaba.fastjson.JSONArray;
    import com.crb.ocms.fund.domain.util.HttpUtil;
    import com.ibm.sc.osp.base.core.util.StringUtils;
    import lombok.extern.slf4j.Slf4j;
    
    import java.lang.reflect.ParameterizedType;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @Project crb-fund
     * @PackageName com.crb.ocms.product.service
     * @ClassName FundHttpTemplate
     * @Author kc
     * @Date 2019/4/4 10:50
     * @Description  走http的公共继承模板方法,第一个泛型为请求的参数类型,第二个参数为返回的参数类型
     */
    @Slf4j
    public abstract class FundHttpTemplate<T,K> {
    
    
    
        /**
         * 地址请求
         * @return 请求地址
         */
        protected abstract String linkHttp();
    
        /**
         * 得到响应数据
         * @param t
         * @return
         */
        public List<K> getData(T t) {
    
            Map<String, String> request_map = new HashMap<>(1);
            request_map.put("Content-Type", "application/json");
            String url = linkHttp();
            //封装请求参数
            String params = getParamsData(t);
            String dataObj = HttpUtil.sendPost(url, params, request_map);
            if (StringUtils.isNotEmpty(dataObj)) {
                try {
                    Class <K> entityClass = (Class <K>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
                    List<K> ts = (List<K>) JSONArray.parseArray(dataObj, entityClass);
                    return ts;
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("获取数据异常原始数据:{}",dataObj);
                    return null;
                }
            } else {
                log.error("获取数据异常");
                return null;
            }
        }
    
        /**
         * 构造参数
         * @param t
         * @return
         */
        protected abstract String getParamsData(T t);
    
    }

    httpUtil:

    package com.crb.ocms.fund.domain.util;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    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.HttpRequestBase;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    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.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URISyntaxException;
    import java.util.ArrayList;
    import java.util.Map;
    /**
     * @Project crb-cost-domain
     * @PackageName com.crb.ocms.cost.cost.util
     * @ClassName HttpUtil
     * @Author kc
     * @Date 2019/2/21 13:39
     * @Description http请求工具类
     */
    @Component
    public class HttpUtil {
        private static PoolingHttpClientConnectionManager cm;
        private static String EMPTY_STR = "";
        private static String UTF_8 = "UTF-8";
    
        private static Integer maxTotal;
    
        private static Integer maxPerRoute;
    
    
        @Value("${httpconfig.maxTotal}")
        public void setMaxTota(Integer maxTotal) {
            HttpUtil.maxTotal = maxTotal;
        }
        @Value("${httpconfig.maxPerRoute}")
        public void setMaxPerRoute(Integer maxPerRoute) {
            HttpUtil.maxPerRoute = maxPerRoute;
        }
    
        private static void init() {
            if (cm == null) {
                cm = new PoolingHttpClientConnectionManager();
                // 整个连接池最大连接数
                cm.setMaxTotal(maxTotal);
                // 每路由最大连接数,默认值是2
                cm.setDefaultMaxPerRoute(maxPerRoute);
            }
        }
    
        /**
         * 通过连接池获取HttpClient
         *
         * @return
         */
        private static CloseableHttpClient getHttpClient() {
            init();
            return HttpClients.custom().setConnectionManager(cm).build();
        }
    
        /**
         * @param url
         * @return
         */
        public static String sendGet(String url) {
            HttpGet httpGet = new HttpGet(url);
            return getResult(httpGet);
        }
    
        /**
         * get请求 带参数
         * @param url
         * @param params
         * @return
         * @throws URISyntaxException
         */
        public static String sendGet(String url, Map<String, String> params) {
            URIBuilder ub = new URIBuilder();
            ub.setPath(url);
            ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
            ub.setParameters(pairs);
            HttpGet httpGet = null;
            try {
                httpGet = new HttpGet(ub.build());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return getResult(httpGet);
        }
    
        /**
         * get请求 带参数带header
         * @param url
         * @param headers
         * @param params
         * @return
         * @throws URISyntaxException
         */
        public static String sendGet(String url, Map<String, String> headers, Map<String, String> params)
        {
            URIBuilder ub = new URIBuilder();
            ub.setPath(url);
            ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
            ub.setParameters(pairs);
            HttpGet httpGet = null;
            try {
                httpGet = new HttpGet(ub.build());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            for (Map.Entry<String, String> param : headers.entrySet()) {
                httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
            return getResult(httpGet);
        }
    
    
        /**
         * post基本请求
         * @param url
         * @return
         */
        public static String sendPost(String url) {
            HttpPost httpPost = new HttpPost(url);
            return getResult(httpPost);
        }
    
        /**
         * post请求 str参数
         * @param url
         * @param param
         * @return
         */
        public static String sendPost(String url,String param) {
            HttpPost httpPost = new HttpPost(url);
            //解决中文乱码问题
            StringEntity entity = new StringEntity(param,"utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            return getResult(httpPost);
        }
    
        /**
         * post请求 带参数
         * @param url
         * @param params
         * @return
         * @throws UnsupportedEncodingException
         */
        public static String sendPost(String url, Map<String, String> params)  {
            HttpPost httpPost = new HttpPost(url);
            ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return getResult(httpPost);
        }
        /**
         * post请求 带参数
         * @param url
         * @param param
         * @param headers
         * @return
         * @throws UnsupportedEncodingException
         */
        public static String sendPost(String url,String param, Map<String, String> headers) {
            HttpPost httpPost = new HttpPost(url);
            //解决中文乱码问题
            StringEntity entity = new StringEntity(param,"utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            for (Map.Entry<String, String> head : headers.entrySet()) {
                httpPost.addHeader(head.getKey(), head.getValue());
            }
            return getResult(httpPost);
        }
    
        /**
         * post请求 带header 带参数
         * @param url
         * @param headers
         * @param params
         * @return
         * @throws UnsupportedEncodingException
         */
        public static String sendPost(String url, Map<String, String> headers, Map<String, String> params)
                throws UnsupportedEncodingException {
            HttpPost httpPost = new HttpPost(url);
            for (Map.Entry<String, String> param : headers.entrySet()) {
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
            ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
    
            return getResult(httpPost);
        }
    
        /**
         * 参数封装
         * @param params
         * @return
         */
        private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, String> params) {
            ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> param : params.entrySet()) {
                pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
            }
            return pairs;
        }
    
        /**
         * 处理Http请求结果
         * @param request
         * @return
         */
        private static String getResult(HttpRequestBase request) {
            CloseableHttpClient httpClient = getHttpClient();
            try {
                CloseableHttpResponse response = httpClient.execute(request);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity,"UTF-8");
                    response.close();
                    return result;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return EMPTY_STR;
        }
    
    }

     实现类:

    package com.crb.ocms.fund.domain.util.http;
    
    import com.alibaba.fastjson.JSONObject;
    import com.crb.ocms.fund.domain.po.PackingDepositAccount;
    import com.crb.ocms.fund.domain.util.http.FundHttpTemplate;
    import com.crb.ocms.fund.domain.vo.req.IcPackingDepositAccountQueryVo;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    /**
     * @Project ocms
     * @PackageName com.crb.ocms.fund.api.config
     * @ClassName IcPackingAccountDepositForHttp
     * @Author 
     * @Date 2019/4/8 0008 上午 11:08
     * @Description
     */
    @Component
    public class IcPackingAccountDepositForHttp extends FundHttpTemplate<IcPackingDepositAccountQueryVo,PackingDepositAccount> {
    
        @Value("${icPackingAccountDeposit.url}")
        private String icPackingAccountDepositUrl;
    
        @Override
        protected String linkHttp() {
            return icPackingAccountDepositUrl;
        }
    
        @Override
        protected String getParamsData(IcPackingDepositAccountQueryVo queryVo) {
            JSONObject param = new JSONObject();
            //param.put("regionCode",queryVo.getRegionCode());
            param.put("corporationId",queryVo.getCorporationId());
            param.put("customerId",queryVo.getCustomerId());
            return param.toJSONString();
        }
    }

     调用类:

            List<PackingDepositAccount> packingDepositAccounts = icPackingAccountDepositForHttp.getData(depositAccountQueryVo);
            if(log.isDebugEnabled()){
                log.debug("通过HTTP查询前端视图数据--代保管账户余额》》》》》》》{}",JSONObject.toJSONString(packingDepositAccounts));
            }
  • 相关阅读:
    软工实践第三次作业(结对第一次作业)
    软工实践第四次作业(团队展示)
    软工实践第二次作业(词频统计)
    软工实践第七次作业(软件产品案例分析 )
    安装cordova和ionic遇到cordova v和ionic v出错的问题,出现SyntaxError
    软工实践第八次作业(软件工程实践总结)
    软工实践第六次作业(团队项目作业汇总)
    软工实践第五次作业(结对第二次作业)
    chain of responsibilit职责链模式
    术语
  • 原文地址:https://www.cnblogs.com/kangchen/p/10802311.html
Copyright © 2020-2023  润新知