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}}