web开发中远程接口的改观用法
工作中,使用webService 以及 rmi 进行远程接口调用, 经常出现 连接不上的 问题.
于是想到利用url直接post或者get方式,提交给其他系统去做处理.
//jsonp跨域时候使用的参数private static final String CALLBACK = "callback" ;//通过actionName来判断对方要调用我们的什么接口private static final String ACTION_NAME = "actionName" ;//接口调用完毕之后,返回给对方的参数名称private static final String KEY_RESULT = "result" ;//接口调用完毕之后,返回给对方的参数名称,这个message只有出错的时候才会有值private static final String KEY_MESSAGE = "message" ; //对方传过来的url的参数名称private String requestData ;public String getRequestData() {return requestData;}public void setRequestData(String requestData) {this.requestData = requestData;}//成功调用接口后,返回 RESP_SUCCESS_JSONprivate static final JSONObject RESP_SUCCESS_JSON;static{// 初始化固定的json结果// success jsonJSONObject json = new JSONObject();json.put(KEY_RESULT, SUCCESS);RESP_SUCCESS_JSON = json;}//调用接口失败后,返回的结果private JSONObject getErrorJson(String msg){JSONObject ret = new JSONObject();ret.put(KEY_RESULT, ERROR);ret.put(KEY_MESSAGE, msg);return ret;}public String execute() throws Exception{// 解析请求数据JSONObject reqJson;String action = "" ;jsonp = this.getHttpServletRequest().getParameter(CALLBACK);try{//取出对方传过来的参数值,一串jsonreqJson = JSONObject.fromObject(requestData);// 取出actionaction = StringUtils.trimToEmpty(reqJson.getString(ACTION_NAME));}catch (Exception e) {outputResultJson(getErrorJson("解析json请求错!" + e.getMessage()));return null;}// 执行接口actionJSONObject respJson = new JSONObject();try{logger.info("xx系统调用接口:" + action);logger.info("传入JSON:" + requestData);//根据不同的actionName 调用不同的处理方法if(action.equalsIgnoreCase("UpdateApply")){// 申请表数据修改respJson = updateApply(reqJson.getJSONObject(KEY_DATA));}else if(action.equalsIgnoreCase("RateNotice")){// 合同费率通知// TODO 优先级稍低 郝晶说先不做respJson = rateNotice(reqJson.getJSONObject(KEY_DATA));}else if(action.equalsIgnoreCase("PickReport")){// 调阅审核报告respJson = pickReport(reqJson.getJSONObject(KEY_DATA));}else if(action.equalsIgnoreCase("AddBlackList")){// 加入黑名单respJson = addBlackList(reqJson.getJSONArray(KEY_DATA));}else if(action.equalsIgnoreCase("updateClicStatus")){// 放款,签订合同,等待放款 更新clic状态respJson = updateClicStatus(reqJson.getJSONObject(KEY_DATA));}}catch (Exception e) { //这里的异常可以处理的更细致一些respJson = getErrorJson("错误!" + e.getMessage());}outputResultJson(respJson);return null;}/**这里是针对jsonp跨域进行的处理,如果对方传了跨域所需的参数CALLBACK过来,并且有值的话,使用jsonp的形式给对方返回值,一般适用于对方采用ajax方法调用我们的接口*/private void outputResultJson(JSONObject resultJson) throws IOException{this.getHttpServletResponse().setCharacterEncoding("UTF-8");if(StringUtils.trimToEmpty(jsonp).length() > 0)this.getHttpServletResponse().getWriter().write(jsonp+"("+resultJson.toString()+")");elsethis.getHttpServletResponse().getWriter().write(resultJson.toString());}private JSONObject updateClicStatus(JSONObject reqJsonData) {String bsTrasnportId = reqJsonData.getString("bsApplyId");String status = reqJsonData.getString("status");logger.info("进件号:"+bsTrasnportId+"状态码:"+status);Environment.getInstance().getService(TransportService.class).updateClicStatus(Long.parseLong(bsTrasnportId), status);return RESP_SUCCESS_JSON;}/** * 获得信审1.0接口地址连接 * @return */private static HttpURLConnection getClic1InterfaceConn() throws Exception{URL u = new URL(Property.getConstants("CHARGE_DETAIL"));HttpURLConnection conn = (HttpURLConnection)u.openConnection();conn.setDoOutput(true);conn.setRequestMethod("POST");conn.setUseCaches(false);return conn;} public static void synLoanData(){ List<Map> mcsMap = new ArrayList<Map>();for(MortgagorContact mc : mcs){//把对象转换成key,value形式的mapmcsMap.add(BeanUtils.describe(mc)); // 组织json JSONObject data = new JSONObject(); data.put("bsApplyId", String.valueOf(trans.getBsApplyId())); data.put("decision", BeanUtils.describe(bd));// 决策信息data.put("contact", mcsMap);// 取联系人data.put("status", StringUtils.trimToEmpty(trans.getProcessNode()));// 进件状态 }// 提交 ,获得其他系统的接口链接HttpURLConnection conn = getClic1InterfaceConn();try{log.info("同步数据JSON:" + data.toString());OutputStream os = conn.getOutputStream();//往接口中提交参数IOUtils.write("act=borrow", os); IOUtils.write("&client=" + URLEncoder.encode(data.toString(), "utf-8"), os);os.flush();os.close();String response = IOUtils.toString(conn.getInputStream());log.info("同步数据给信审1.0,[Response:" + response + "]");}finally{conn.disconnect();}}//根据不同的actionName 调用不同的处理方法根据参数 action的值,去判断调用哪个service方法.