来源:http://www.51testing.com/
controller层:
@RequestMapping(value = "/S02IF2001.html", method = { RequestMethod.GET, RequestMethod.POST })
public String getOrgList(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("【S02IF2001:获取网点】接口请求");
// 初期化
// Map<String, Object> requestMap =
// JsonUtil.toBean(request.getParameter("RequestJson"), Map.class);
Map<String, Object> requestMap = HttpUtil.getRequestParam(request);
try {
boolean chkFlg = this.checkReqParam(response, requestMap);
if (!chkFlg) {
return null;
}
List<OrgVO> orgList = appOpenInterfaceService.getOrgList();
if (orgList != null && !orgList.isEmpty()) {
this.setReturnPrm(response, CmnMsg.MSG_CODE_1000, orgList);
} else {
this.setReturnPrm(response, CmnMsg.MSG_CODE_1002, null);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
throw e;
}
return null;
}
检测:
/**
* 检查请求参数
*
* @param response
* @param flg
* @param code
* @param msg
* @param data
* @throws IOException
*/
private boolean checkReqParam(HttpServletResponse response, Map<String, Object> requestMap) throws IOException {
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
// 非法请求
if (requestMap == null || StringUtil.isNull(requestMap.get("orgCode"))) {
this.setReturnPrm(response, CmnMsg.MSG_CODE_2001, null);
return false;
}
String token = StringUtil.nvl(requestMap.get("token"));
String timestamp = StringUtil.nvl(requestMap.get("timestamp"));
String signature = StringUtil.nvl(requestMap.get("signature"));
// 分行编码
String orgCode = StringUtil.nvl(requestMap.get("orgCode"));
// token不一致
if (!TokenManager.checkToken(token)) {
this.setReturnPrm(response, CmnMsg.MSG_CODE_2003, null);
return false;
}
Map<String, String> signPrm = new HashMap<String, String>();
signPrm.put("token", token);
signPrm.put("timestamp", timestamp);
signPrm.put("orgCode", orgCode);
// 签名检查
boolean chkResult = ParamSignUtils.validateSign(signature, signPrm, CmnConstance.SIGN_STR);
if (!chkResult) {
this.setReturnPrm(response, CmnMsg.MSG_CODE_2002, null);
return false;
}
return true;
}
/**
* 设置返回参数
*
* @param response
* @param flg
* @param code
* @param msg
* @param data
* @throws IOException
*/
private void setReturnPrm(HttpServletResponse response, String code, Object data) throws IOException {
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("retCode", code);
retMap.put("data", data);
/* 设置格式为text/json */
response.setContentType("text/json");
/* 设置字符集为'UTF-8' */
response.setCharacterEncoding("UTF-8");
response.getWriter().println(JsonUtil.toJson(retMap));
}
/**
* 字符串转二进制
*
* @param str
* 要转换的字符串
* @return 转换后的二进制数组
*/
public static byte[] hex2byte(String str) { // 字符串转二进制
if (str == null)
return null;
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1)
return null;
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}
测试:
public static void main(String[] args) {
Map<String, Object> reqMap = new HashMap<String, Object>();
// 机构代码
reqMap.put("OrgCode", "5001");
// 核心接口TxCode:S03IF3001-获取设备媒体发布信息
reqMap.put("TxCode", "S02IF2018");
reqMap.put("phoneNo", "2018-08-20");
reqMap.put("Resource", "appIF");
reqMap.put("ClassifyCode", "01");
reqMap.put("BusinessType", "0000");
// 0:现场取号
reqMap.put("ChannelType", "0");
reqMap.put("TicketType", "0");
Map<String, Object> retMap = HttpUtil.reqOpenIF(reqMap);
System.err.println(retMap);
}
/**
* 获取访问地址
*
* @param host
* @param port
* @param txCode
* @return
*/
public static Map<String, Object> reqOpenIF(Map<String, Object> prmMap) {
String retStr = "";
Map<String, Object> retMap = null;
try {
String coreHost = IniUtil.getValue("CoreHost");
String corePort = IniUtil.getValue("CorePort");
String resource = StringUtil.nvl(prmMap.get("Resource"));
String txCode = StringUtil.nvl(prmMap.get("TxCode"));
String orgCode = StringUtil.nvl(prmMap.get("OrgCode"));
String filePath = StringUtil.nvl(prmMap.get("FilePath"));
prmMap.remove("TxCode");
prmMap.remove("Resource");
if ("".equals(token)) {
// 获取动态token
token = HttpUtil.getToken(coreHost, corePort, orgCode);
}
String reqUrl = getUrl(coreHost, corePort, resource, txCode);
String timestamp = DateUtil.getTimestamp(DateUtil.getTodayDateTime());
Map<String, String> signPrmMap = new HashMap<String, String>();
signPrmMap.put("token", token);
signPrmMap.put("timestamp", timestamp);
signPrmMap.put("orgCode", orgCode);
String signature = ParamSignUtils.sign(signPrmMap, CmnConstance.SIGN_STR);
signPrmMap.put("signature", signature);
Map<String, Object> accMap = new HashMap<String, Object>();
accMap.putAll(signPrmMap);
accMap.put("reqData", prmMap);
// 有附件上传的情况
if (!"".equals(filePath)) {
retStr = HttpUtil.httpPostMultipart(reqUrl, JsonUtil.toJson(accMap), filePath);
} else {
retStr = HttpUtil.getHttpPostX(reqUrl, JsonUtil.toJson(accMap));
}
if (StringUtil.isNotNull(retStr)) {
retMap = JsonUtil.toBean(retStr, Map.class);
if (CmnConstance.MSG_CODE_2003.equals(retMap.get("retCode"))) {
// 获取动态token
token = HttpUtil.getToken(coreHost, corePort, orgCode);
timestamp = DateUtil.getTimestamp(DateUtil.getTodayDateTime());
signPrmMap = new HashMap<String, String>();
signPrmMap.put("token", token);
signPrmMap.put("timestamp", timestamp);
signPrmMap.put("orgCode", orgCode);
signature = ParamSignUtils.sign(signPrmMap, CmnConstance.SIGN_STR);
signPrmMap.put("signature", signature);
accMap = new HashMap<String, Object>();
accMap.putAll(signPrmMap);
accMap.put("reqData", prmMap);
retStr = HttpUtil.getHttpPostX(reqUrl, JsonUtil.toJson(accMap));
if (StringUtil.isNotNull(retStr)) {
retMap = JsonUtil.toBean(retStr, Map.class);
} else {
logger.debug("=========接口返回值为空。业务系统接口访问失败=========");
throw new BasicException("90002", "接口返回值为空。业务系统接口访问失败");
}
}
} else {
logger.debug("=========接口返回值为空。业务系统接口访问失败=========");
throw new BasicException("90002", "接口返回值为空。业务系统接口访问失败");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("90001:连接超时或网络异常");
throw new BasicException("90001", "连接超时或网络异常");
}
return retMap;
}
/**
* 获取令牌
*
* @return
*/
public static String getToken(String host, String port, String orgCode) {
String token = "";
// 调用业务系统同步账户信息接口
String dateTime = DateUtil.getTodayDateTime();
String timestamp = DateUtil.getTimestamp(dateTime);
Map<String, String> signPrmMap = new HashMap<String, String>();
signPrmMap.put("token", CmnConstance.TOKEN_STR);
signPrmMap.put("timestamp", timestamp);
// 网点代码
signPrmMap.put("orgCode", orgCode);
String signature = ParamSignUtils.sign(signPrmMap, CmnConstance.SIGN_STR);
signPrmMap.put("signature", signature);
Map<String, Object> accMap = new HashMap<String, Object>();
accMap.putAll(signPrmMap);
accMap.put("data", "");
try {
String reqUrl = "http://" + host + ":" + port + "/sbank-core/commonIF/getToken.html";
// 通过开放接口获取窗口信息
String retStr = HttpUtil.getHttpPostX(reqUrl, JsonUtil.toJson(accMap));
if (StringUtil.isNotNull(retStr)) {
Map<String, Object> retMap = JsonUtil.toBean(retStr, Map.class);
if (CmnConstance.MSG_CODE_1000.equals(retMap.get("retCode"))) {
token = String.valueOf(retMap.get("data"));
} else {
throw new BasicException(MsgUtil.getMessage(String.valueOf(retMap.get("retCode"))));
}
} else {
throw new BasicException("接口返回值为空。核心接口系统接口访问失败");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("通信异常。核心接口系统接口访问失败");
}
return token;
}
/**
* HttpPost取得数据
*
* @param strUrl
* 网址
* @param data
* JSON/XML数据
* @return JSON/XML
*/
public static String getHttpPostX(String strUrl, String data) throws BasicException {
InputStream instr = null;
java.io.ByteArrayOutputStream out = null;
try {
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// connection.setReadTimeout(10 * 1000);
connection.connect();
// DataOutputStream printout = new
// DataOutputStream(connection.getOutputStream());
PrintWriter printout = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
printout.write(data.toString());
printout.flush();
printout.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
// lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
// builder.appendln(sb);
reader.close();
// 断开连接
connection.disconnect();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
logger.error("90001:连接超时或网络异常");
throw new BasicException("90001", "连接超时或网络异常");
} finally {
try {
if (out != null) {
out.close();
}
if (instr != null) {
instr.close();
}
} catch (Exception ex) {
logger.error("90001:连接超时或网络异常");
throw new BasicException("90001", "连接超时或网络异常");
}
}
}