需要调用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));
}

java模板模式项目中使用--封装一个http请求工具类的更多相关文章

  1. swift项目第十天:网络请求工具类的封装

    import UIKit /* 必须先导入头文件:import AFNetworking */ import AFNetworking //MARK:-0:定义枚举:以枚举定义请求网络的get和pos ...

  2. java生成图片验证码(转)--封装生成图片验证码的工具类

    博客部分内容转载自 LonlySnow的博客:后台java 实现验证码生成 1.controller方法 @RequestMapping(value = "/verifycode/img&q ...

  3. 基于AFNetworking封装的网络请求工具类【原创】

    今天给大家共享一个我自己封装的网络请求类,希望能帮助到大家. 前提,导入AFNetworking框架, 关于修改AFN源码:通常序列化时做对text/plan等的支持时,可以一劳永逸的修改源代码,在a ...

  4. (转)关于java和web项目中的相对路径问题

    原文:http://blog.csdn.net/yethyeth/article/details/1623283 关于java和web项目中的相对路径问题 分类: java 2007-05-23 22 ...

  5. python+selenium之自定义封装一个简单的Log类

    python+selenium之自定义封装一个简单的Log类 一. 问题分析: 我们需要封装一个简单的日志类,主要有以下内容: 1. 生成的日志文件格式是 年月日时分秒.log 2. 生成的xxx.l ...

  6. Python之自定义封装一个简单的Log类

    参考:http://www.jb51.net/article/42626.htm 参考:http://blog.csdn.net/u011541946/article/details/70198676 ...

  7. Python+Selenium中级篇之8-Python自定义封装一个简单的Log类《转载》

    Python+Selenium中级篇之8-Python自定义封装一个简单的Log类: https://blog.csdn.net/u011541946/article/details/70198676

  8. java内部类、接口、集合框架、泛型、工具类、实现类

    .t1 { background-color: #ff8080; width: 1100px; height: 40px } 一.内部类 1.成员内部类. (1)成员内部类的实例化: 外部类名.内部类 ...

  9. Redis进阶实践之九 独立封装的RedisClient客户端工具类(转载9)

    Redis进阶实践之九 独立封装的RedisClient客户端工具类 一.引言 今天开始有关Redis学习的第九篇文章了,以后肯定会大量系统使用Redis作为缓存介质,为了更好的更好的Redis,自己 ...

随机推荐

  1. [转]地理投影,常用坐标系详解、WGS84、WGS84 Web墨卡托、WGS84 UTM、北京54坐标系、西安80坐标系、CGCS2000坐标系

    转自:http://www.rivermap.cn/docs/show-1829.html 常用坐标系详解 (一)WGS84坐标系 WGS-84坐标系(World Geodetic System一19 ...

  2. openresty开发系列18--lua的字符串string操作

    openresty开发系列18--lua的字符串string操作 string的相关操作 1)string.upper(s)接收一个字符串 s,返回一个把所有小写字母变成大写字母的字符串.print( ...

  3. [译]如何在GitHub仓库创建一个标签tag, 并推送到远程分支?

    问: 我在GitHub上有一个仓库,我需要给他打个tag.我在shell打了tag,但是在Github上没有显示出来.我还要做其他什么么? 我在shell中使用的命令是: git tag 2.0 当我 ...

  4. c# Invoke的新用法

    在C# 3.0及以后的版本中有了Lamda表达式,像上面这种匿名委托有了更简洁的写法..NET Framework 3.5及以后版本更能用Action封装方法.例如以下写法可以看上去非常简洁: voi ...

  5. ip地址分类和网段详解

    IP地址分类/IP地址10开头和172开头和192开头的区别/判断是否同一网段 简单来说在公司或企业内部看到的就基本都是内网IP,ABC三类IP地址里的常见IP段. 每个IP地址都包含两部分,即网络号 ...

  6. css代码陷阱

    1.选择器优先级 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  7. LODOP注册语句相关简短问答

    注册和角色相关博文:LODOP.C-LODOP注册号的区别.Lodop客户端本地角色注册号常见误区.Lodop.c-lodop注册与角色简短问答.LODOP和C-LODOP注册与角色等简短问答[增强版 ...

  8. 触屏Tap模拟事件

    触屏的click因为有双击判断所以有200ms的延迟,zepto里的touch.js兼容不好所以tap也没法直接用. gibhub上有个fastclick太大了. 自己用touched写个简单的模拟t ...

  9. 15点睛Spring4.1-TaskExecutor

    转发:https://www.iteye.com/blog/wiselyman-2212679 15.1 TaskExecutor spring的TaskExecutor为在spring环境下进行并发 ...

  10. Java基础教程:垃圾回收

    Java基础教程:垃圾回收 垃圾回收 垃圾回收(Garbage Collection,GC),顾名思义是释放垃圾占用的空间,防止内存泄漏.有效的使用可以使用的内存,对内存堆中已经死亡的或者长时间没有使 ...