• 接口代码整理


    1.调用接口:

    (1)http协议工具类:

     1 /**
     2  * 
     3  */
     4 package kklazy.test.utils;
     5 
     6 import java.io.IOException;
     7 import org.apache.http.HttpEntity;
     8 import org.apache.http.StatusLine;
     9 import org.apache.http.client.methods.CloseableHttpResponse;
    10 import org.apache.http.client.methods.HttpPost;
    11 import org.apache.http.entity.StringEntity;
    12 import org.apache.http.impl.client.CloseableHttpClient;
    13 import org.apache.http.impl.client.HttpClients;
    14 import org.apache.http.util.EntityUtils;
    15 
    16 /**
    17  * @author whh
    18  * http协议工具类
    19  */
    20 public class HttpUtils {
    21     
    22     /**
    23      * 调用接口
    24      * @param url 被调用接口的IP地址
    25      * @param msg 上送json数据
    26      * @param charset 编码格式
    27      * @return
    28      */
    29     public static String callInterface(String url, String msg, String charset){
    30         //组装设置请求参数
    31         StringEntity requestEntity = new StringEntity(msg, charset);
    32         requestEntity.setContentEncoding(charset);
    33         requestEntity.setContentType("text/json");
    34         //创建一个httpclient对象
    35         CloseableHttpClient  httpClient = null;
    36         //创建post对象
    37         HttpPost httpPost = new HttpPost(url);
    38         httpPost.setEntity(requestEntity);
    39         String entityStr = null;        
    40         try {
    41             httpClient = HttpClients.createDefault();//创建默认的httpClient实例
    42             CloseableHttpResponse  httpResponse = httpClient.execute(httpPost);//执行请求
    43             try{
    44                 HttpEntity entity = httpResponse.getEntity();    
    45                 entityStr = EntityUtils.toString(entity,"utf-8");            
    46                 System.out.println("接口响应返回内容:"+entityStr);  
    47             } finally{
    48                 //关闭httpclient连接,释放资源
    49                 httpResponse.close();
    50             } 
    51             StatusLine statusLine = httpResponse.getStatusLine();            
    52             int statusCode = statusLine.getStatusCode();//获取响应的结果            
    53             System.out.println("statusCode:"+statusCode);            
    54             
    55         } catch (Exception e) {   
    56             
    57         }finally{
    58             if(null != httpClient){
    59                 try {
    60                     httpClient.close();
    61                 } catch (IOException e) {
    62                     e.printStackTrace();
    63                 }
    64             }
    65             
    66         }
    67         return entityStr;
    68     }
    69 
    70 }

    (2)接口参数类:

     1 /**
     2  * 
     3  */
     4 package kklazy.test.entity;
     5 
     6 /**
     7  * @author whh
     8  * 调用接口参数
     9  */
    10 public class ApiParam {
    11     /**
    12      * 
    13      */
    14     private String version ;//版本号 1.0
    15     private String reqType;//交易类型:15
    16     private String desc;//说明
    17     /**
    18      * @return the version
    19      */
    20     public String getVersion() {
    21         return version;
    22     }
    23     /**
    24      * @param version the version to set
    25      */
    26     public void setVersion(String version) {
    27         this.version = version;
    28     }
    29     /**
    30      * @return the reqType
    31      */
    32     public String getReqType() {
    33         return reqType;
    34     }
    35     /**
    36      * @param reqType the reqType to set
    37      */
    38     public void setReqType(String reqType) {
    39         this.reqType = reqType;
    40     }
    41     /**
    42      * @return the desc
    43      */
    44     public String getDesc() {
    45         return desc;
    46     }
    47     /**
    48      * @param desc the desc to set
    49      */
    50     public void setDesc(String desc) {
    51         this.desc = desc;
    52     }
    53 }

    (3)HttpService:

     1 package kklazy.test.service;
     2 
     3 import java.util.ArrayList;
     4 import java.util.HashMap;
     5 import java.util.Iterator;
     6 import java.util.List;
     7 import java.util.Map;
     8 import org.springframework.stereotype.Service;
     9 import org.springframework.transaction.annotation.Transactional;
    10 import com.alibaba.fastjson.JSON;
    11 import kklazy.test.entity.ApiParam;
    12 import kklazy.test.utils.HttpUtils;
    13 import net.sf.json.JSONArray;
    14 import net.sf.json.JSONObject;
    15 
    16 /**
    17  * @author whh
    18  */
    19 @Service
    20 @Transactional(rollbackFor = Exception.class)
    21 public class HttpService  {
    22     
    23     public void callInterface(){
    24         ApiParam apiParam  = new  ApiParam();
    25         apiParam.setVersion("1.0");//版本号
    26         apiParam.setReqType("15");//交易类型:固定值15
    27         apiParam.setDesc("ABC");//说明
    28         Map<String,Object> map = new HashMap<String,Object>();
    29         map.put("requestData",apiParam);//存入map,key为:requestData
    30         map.put("signature","111111");//签名:内部使用暂不验签
    31         /**
    32          * 需要发送的json数据格式为:
    33          * {"requestData":{"version":"1.0","reqType":"15","desc":"aaa"},"signature":"11111111"}
    34          */
    35         //map转换成json
    36         String jsonMsg = JSON.toJSONString(map,true);
    37         System.out.println("调用XX系统接口参数值:"+jsonMsg);
    38         String responseJson = HttpUtils.callInterface("http://192.168.17.61:9805/UAT/receipt/refund.json", jsonMsg, "UTF-8");//调用接口
    39         Map<String, Object> responseMap = parseJSONToMap(responseJson);
    40         //获取XX系统返回信息:应答码,响应信息
    41         String  respCode = (String) responseMap.get("respCode");
    42         String  respMsg  = (String) responseMap.get("respMsg");
    43         System.out.println("XX系统返回responseMap:应答码:"+respCode+",响应信息:"+respMsg);
    44         
    45     }
    46     
    47     /**
    48      * json转换成map类型
    49      * @param jsonStr
    50      * @return
    51      */
    52   public  Map<String, Object> parseJSONToMap(String jsonStr){
    53         Map<String,Object> map = new HashMap<String, Object>();
    54         //最外层解析
    55         JSONObject    json = JSONObject.fromObject(jsonStr);
    56         for(Object k :json.keySet()){
    57             Object v = json.get(k);
    58             //如果内层还是数组的话,继续解析
    59             if(v instanceof JSONArray){
    60                 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
    61                 @SuppressWarnings("unchecked")
    62                 Iterator<JSONObject> it = ((JSONArray)v).iterator();
    63                 while(it.hasNext()){
    64                     JSONObject json2 = it.next();
    65                     list.add(parseJSONToMap(json2.toString()));
    66                 }
    67                 map.put(k.toString(), list);
    68             }else{
    69                 map.put(k.toString(), v);
    70             }
    71         }
    72         return map;
    73     }
    74     
    75 }

     2.被调用接口:

    (1)InterfaceController:

      1 /**
      2  * 
      3  */
      4 package kklazy.test.controller;
      5 
      6 import java.util.HashMap;
      7 import java.util.List;
      8 import java.util.Map;
      9 import javax.servlet.http.HttpServletRequest;
     10 import javax.servlet.http.HttpServletResponse;
     11 import org.springframework.beans.factory.annotation.Autowired;
     12 import org.springframework.stereotype.Controller;
     13 import org.springframework.ui.ModelMap;
     14 import org.springframework.web.bind.annotation.RequestBody;
     15 import org.springframework.web.bind.annotation.RequestMapping;
     16 import org.springframework.web.bind.annotation.ResponseBody;
     17 import kklazy.api.model.TransAmtWhiteListEntity;
     18 import kklazy.api.service.TransAmtWhiteListService;
     19 import kklazy.api.utils.JSONHelpUtils;
     20 import kklazy.common.controller.BasePageController;
     21 import kklazy.persistence.service.PageService;
     22 import kklazy.persistence.utils.DateUtils;
     23 import kklazy.persistence.utils.StringUtils;
     24 /**
     25  * 接口(被调用)
     26  * @author whh
     27  *
     28  */
     29 @Controller
     30 @RequestMapping("interfaceController")
     31 public class InterfaceController extends BasePageController<TransAmtWhiteListEntity, String> {
     32 
     33     @Autowired
     34     private TransAmtWhiteListService transAmtWhiteListService;
     35     @Override
     36     public PageService<TransAmtWhiteListEntity, String> pageservice() {
     37         return transAmtWhiteListService;
     38     }
     39 
     40     @Override
     41     public String path() {
     42         return "";
     43     }
     44 
     45     /**
     46      * @param request
     47      * @param response
     48      * @param modelMap
     49      * @return
     50      */
     51     @SuppressWarnings("unchecked")
     52     @ResponseBody
     53     @RequestMapping(value = "match")//@RequestBody一般情况下来说常用其来处理application/json类型:接收json格式的请求报文
     54     public Map<String, Map<String, String>> match(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap,@RequestBody String requetData) {
     55         Map<String, Object> requestBody ;
     56         Map<String, Object> header;
     57         Map<String, Object> body ;
     58         Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();//响应结果
     59         //若请求数据为空,给出提示
     60         if(StringUtils.isBlank(requetData)){
     61             Map<String, String> data = new HashMap<String, String>();
     62             data.put("code","9999");
     63             data.put("message","请求信息不合格(都为空),请重新发送");
     64             result.put("data",data );
     65             return result;
     66         }
     67         
     68         //获取请求报文header和body中参数
     69         requestBody = JSONHelpUtils.parseJSONToMap(requetData);//json->map
     70         System.out.println("请求信息:"+requestBody.toString());
     71         header = (Map<String, Object>) requestBody.get("HEADER");
     72 body = (Map<String, Object>) requestBody.get("BODY");
     73         //校验请求信息是否合格
     74         if(null ==header || header.size() <= 0){
     75             Map<String, String> data = new HashMap<String, String>();
     76             data.put("code","9999");
     77             data.put("message","请求信息不合格(HEADER为空),请重新发送");
     78             result.put("data",data );
     79             return result;
     80         }
     81         if(null ==body || body.size() <= 0){
     82             Map<String, String> data = new HashMap<String, String>();
     83             data.put("code","9999");
     84             data.put("message","请求信息不合格(BODY为空),请重新发送");
     85             result.put("data",data );
     86             return result;
     87         }
     88         //解析请求报文中header
     89         String ver = (null!=header.get("VER")?header.get("VER").toString():null);         //版本号1.00
     90         String sn = (null!=header.get("SN")?header.get("SN").toString():null);              // 请求流水号(同一发起方每次发起的风控请求时,每次送不同的值。便于后续定位风控流水的查询。)
     91         String reqFrom = (null!=header.get("REQ_FROM")?header.get("REQ_FROM").toString():null);// 请求来源  商户前置:MER_FRONT   C核心:C_CORE
     92         String tci = (null!=header.get("TCI")?header.get("TCI").toString():null);         //Transcation Channel Identifier交易渠道标识
     93         String resDt = DateUtils.format("yyyyMMddHHmmss");//获取当前时间为请求响应时间
     94         String resv1 = (null!=header.get("RESV1")?header.get("RESV1").toString():null);     // 保留域1
     95         //封装响应报文header
     96         Map<String, String> headerResult = new HashMap<String, String>();
     97         headerResult.put("VER", ver);
     98         headerResult.put("SN", sn);
     99         headerResult.put("REQ_FROM", reqFrom);
    100         headerResult.put("TCI", tci);
    101         headerResult.put("PROC_DT", resDt);
    102         headerResult.put("RESV1", resv1);
    103         result.put("HEADER", headerResult);
    104         //解析body中字段并进行处理
    105         String formId = (null!=body.get("FORM_ID")?body.get("FORM_ID").toString():null);//长度为15位。
    106         Map<String, String> bodyResult = new HashMap<String, String>();//把响应报文中body封装为bodyResult
    107         //校验:formId比较重要,若为空,直接打回
    108         if (StringUtils.isBlank(formId)) {
    109             bodyResult.put("RSP_CODE", "1111");
    110             bodyResult.put("RSP_MSG", "FORM_ID不能为空");
    111             result.put("BODY", bodyResult);
    112             return result;
    113         }
    114         //当formId为“AvailabilityTest”时,表明用户的请求用于检查接口的可用性。此时,应立刻返回成功报文给用户。
    115         if("AvailabilityTest".equals(formId)){
    116             bodyResult.put("RSP_CODE", "0000");
    117             bodyResult.put("RSP_MSG", "接口可用");
    118             result.put("BODY", bodyResult);
    119             return result;
    120         }
    121         String orgNo = (null!=body.get("ORG_NO")?body.get("ORG_NO").toString():null);                // 机构号(前端)
    122         String merchNo = (null!=body.get("MERCH_NO")?body.get("MERCH_NO").toString():null);            // 商户号(前端)
    123         String transAmt = (null!=body.get("TRANS_AMT")?body.get("TRANS_AMT").toString():null);        // 交易金额
    124         
    125         /**
    126          * 根据机构号,商户号,交易金额和是允许任意金额标志否查询是否存在满足条件的数据
    127          * 若查询到记录,则
    128          * (若存在,则说明1.不需规定金额过滤;2.符合白名单金额规则;否则,就是支付金额不符合规定)
    129          */
    130         StringBuilder sb = new StringBuilder("select count(*) from dual where exists ( SELECT 1 FROM  YST_TRANS_AMT_WHITE_LIST t where t.is_delete='0' and t.status='1' ");
    131         sb.append(" and t.form_id='"+formId+"' ");
    132         if(StringUtils.isNotBlank(orgNo)){
    133             sb.append(" and t.org_no='"+orgNo+"' ");
    134         }
    135         if(StringUtils.isNotBlank(merchNo)){
    136             sb.append(" and t.merch_no='"+merchNo+"' ");
    137         }
    138         sb.append(" and (t.flag_all_amt='1' or (t.flag_all_amt='0' and t.allowed_amt='"+transAmt+"' ))) ");
    139         @SuppressWarnings("unchecked")
    140         List<Object> count= (List<Object>) transAmtWhiteListService.findByNativeSql(sb);
    141         //当查寻出isExist为0时,说明数据库不存在满足条件的白名单,当为1时,存在满足条件的白名单记录
    142         String isExist=     count.get(0).toString();
    143         bodyResult.put("RSP_CODE", "0000");
    144         bodyResult.put("RSP_MSG", "OK");
    145         if("0".equals(isExist)){
    146             bodyResult.put("RSP_CODE", "9999");
    147        bodyResult.put("RSP_MSG", "支付金额不符合规定");
    148         }
    149         result.put("BODY", bodyResult);
    150         
    151         System.out.println("响应信息:"+result.toString());
    152         return result;
    153     }
    154     
    155     
    156 }

    (2)JSONHelpUtils:

     1 package kklazy.api.utils;
     2 
     3 import java.util.ArrayList;
     4 import java.util.HashMap;
     5 import java.util.Iterator;
     6 import java.util.List;
     7 import java.util.Map;
     8 
     9 import net.sf.json.JSONArray;
    10 import net.sf.json.JSONObject;
    11 
    12 /**
    13  * @author14  *
    15  */
    16 public class JSONHelpUtils {
    17     /**
    18      * json转换成map类型
    19      * @param jsonStr
    20      * @return
    21      */
    22   public static Map<String, Object> parseJSONToMap(String jsonStr){
    23         Map<String,Object> map = new HashMap<String, Object>();
    24         //最外层解析
    25         JSONObject    json = JSONObject.fromObject(jsonStr);
    26         for(Object k :json.keySet()){
    27             Object v = json.get(k);
    28             //如果内层还是数组的话,继续解析
    29             if(v instanceof JSONArray){
    30                 List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
    31                 @SuppressWarnings("unchecked")
    32                 Iterator<JSONObject> it = ((JSONArray)v).iterator();
    33                 while(it.hasNext()){
    34                     JSONObject json2 = it.next();
    35                     list.add(parseJSONToMap(json2.toString()));
    36                 }
    37                 map.put(k.toString(), list);
    38             }else{
    39                 map.put(k.toString(), v);
    40             }
    41         }
    42         return map;
    43     }
    44     
    45   }

    (3)使用Postman发送请求:

    方式一:直接url后面跟参:

    http://localhost:8080/AAA/interfaceController/match?body={"FORM_ID":" AvailabilityTest","ORG_NO":"","MERCH_NO":" 123456789012345","TERM_NO":null,"ACCT_NO":"01","TRANS_AMT":"2015-11-17 11:16:59","TRANS_TYPE":null}

    方式二:json格式

    http://localhost:8080/AAA/interfaceController/match

    {"HEADER":{"VER":"1.0","SN":"31231","REQ_FROM":"MER_FRONT","TCI":"WECHAT_H5","PROC_DT":"20170717153555","RESV1":null},

    "BODY":{"FORM_ID":"000000000008643","ORG_NO":"61000016","MERCH_NO":"939310058120001","TERM_NO":null,"ACCT_NO":"01","TRANS_AMT":"0000000011000","TRANS_TYPE":null}}

  • 相关阅读:
    nyoj 202 红黑树
    nyoj 237 游戏高手的烦恼
    nyoj 203 三国志
    nyoj 118 修路方案
    nyoj 714 Card Trick
    nyoj 710 外星人的供给站
    nyoj 712探 寻 宝 藏
    nyoj 709 异 形 卵
    nyoj 711 最舒适的路线
    HTML5表格简单应用案例之[招聘需求表]
  • 原文地址:https://www.cnblogs.com/whhjava/p/9768016.html
Copyright © 2020-2023  润新知