前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >接口的编写与测试

接口的编写与测试

作者头像
顾翔
发布2019-12-11 12:39:47
7550
发布2019-12-11 12:39:47
举报
文章被收录于专栏:啄木鸟软件测试

来源:http://www.51testing.com/

controller层:

代码语言:javascript
复制
@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;

  }

  }

测试

代码语言:javascript
复制
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", "连接超时或网络异常");

  }

  }

  }
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-09-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 软件测试培训 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
图像处理
图像处理基于腾讯云深度学习等人工智能技术,提供综合性的图像优化处理服务,包括图像质量评估、图像清晰度增强、图像智能裁剪等。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档