restful风格接口

来源:互联网 发布:维多利亚女王 知乎 编辑:程序博客网 时间:2024/05/23 13:25


关于什么是restful接口,资料解释遍地都是,自认为解释不清。现在只是记录一个普通的接口请求,在工作中见过不同人写的rest接口,风格不同,现在说说自己的看法。

两个问题:
一,Controller方法,以什么样的形式入参?实体封装参数 or 直接传递参数

二,rest风格接口,到底给请求方返回什么?越纯洁越好 or 除了请求json、xml数据还带上状态码,错误信息,成功失败标识。
比较以下案例:
A,1,2:包含异常码,状态码。4,只包含状态码。3,包含成功标识符,异常码,异常信息,时间撮。
B,1,2:把返回信息直接封装在一个实体中,没有定义泛型。4,用ResponseEntity接收响应数据。3,自定义泛型。

案例:
一,
(武汉公积金)
1,get方法:
@RequestMapping(value = "/gjjmp/{payCityID}_{idno}_{name}", method = RequestMethod.GET)
public IcsGjjMpCrResponse getGjjMpCr(@PathVariable String payCityID, @PathVariable String idno, @PathVariable String name) {}

2,post方法:
@RequestMapping(value = "/gjjmp")
public IcsGjjMpCrResponse checkGjjMpCr (@RequestBody IcsGjjMpCrRequest rq){}

1,2请求路径及参数
Http get:
http://10.14.15.216:8081/gjjmp/420100_420104197107260410_沈克

Http post:
http://10.14.15.216:8081/gjjmp/
Content-Type=application/json
{"payCityID":"420100","idno":"420104197107260410","name":"沈克","immediate":"t"}

(鹏元反欺诈)
3,get/post
@Controller
@RequestMapping("/credit")
public class PyCreditQueryController {

@RequestMapping(path = "/queryPy", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public ResponseResult<CisReportRoot> queryPy(HttpServletRequest request,PyQueryBean pyQueryBean) {}
}

Http get:
http://10.14.15.216:8080/ics.credit/credit/queryPy?name=沈克&cardId=34122&phone=18298182579
Http post:与上类似

4,
    @RequestMapping(path = "/queryPy/{name}{cardId}{phone}", method = {RequestMethod.GET})

    public ResponseEntity<CisReportRoot> responseEntityStatusCode(@PathVariable String name, @PathVariable String cardId, @PathVariable String phone) {}

代码:

反欺诈:

@RequestMapping(path = "/queryPy{}", method = {RequestMethod.GET, RequestMethod.POST})@ResponseBodypublic ResponseResult<CisReportRoot> queryPy(HttpServletRequest request,PyQueryBean pyQueryBean) {    ResponseResult<CisReportRoot> responseResult = new ResponseResult<>();    try {        CisReportRoot cisReportRoot = pyQueryService.queryCisReport(pyQueryBean);        responseResult.setData(cisReportRoot);        responseResult.setRefID(pyQueryBean.getRefID());        responseResult.setTimestamp(DateUtil.getTimeStamp().toString());        responseResult.setRet(SUCCESS);    } catch (CreditException e) {        responseResult.setErrorCode(e.getErrorCode());        responseResult.setRet(SUCCESS);        responseResult.setErrorMsg(e.getMessage());    } catch (Exception e) {        responseResult.setErrorCode(PyCreditServiceErrorEnum.SYSTEM_ERROR.getCode());        responseResult.setRet(FAILED);        responseResult.setErrorMsg(PyCreditServiceErrorEnum.SYSTEM_ERROR.getMsg());    }    return responseResult;}@RequestMapping(path = "/queryPy/{name}/{cardId}/{phone}", method = {RequestMethod.GET})public ResponseEntity<CisReportRoot> responseEntityStatusCode(@PathVariable String name, @PathVariable String cardId, @PathVariable String phone) {    CisReportRoot cisReportRoot = null;    PyQueryBean pyQueryBean = new PyQueryBean();    pyQueryBean.setName(name);    pyQueryBean.setPhone(phone);    pyQueryBean.setDocumentNo(cardId);    try {        cisReportRoot = pyQueryService.queryCisReport(pyQueryBean);        // 如果不存在,返回404        if (cisReportRoot == null) {            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);        }        return ResponseEntity.ok(cisReportRoot);        //return new ResponseEntity<>(cisReportRoot, HttpStatus.OK);    } catch (Exception e) {        e.printStackTrace();        // 如果有异常,返回500状态码        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);    }}
武汉公积金

/** * controller主方法 POST * @param rq * @return */@RequestMapping(value="/gjjmp")public IcsGjjMpCrResponse checkGjjMpCr(@RequestBody IcsGjjMpCrRequest rq) {      rq.setUuid(bean.getUuid());   rq.setLocalServerInfo(bean.getLocalHost());      logger.info("REQUEST [POST] "+ getURI()+ "BODY: " +DataConvert.toJson(rq));   writeServerAccessLog(getURI(),"POST","ONCALL",DataConvert.toJson(rq));   IcsGjjMpCrResponse rs = null;      //平台服务类   ISwitchService gjjApiService = serviceMap.get("checkMpRouting");   //缓存服务类   if (!"t".equalsIgnoreCase(rq.getImmediate())) {      // 先调用缓存服务      rs = cacheService.readCache(rq);      if (rs != null) {         writeServerAccessLog(getURI(),"POST","ONCACHE","RESPONSE:"+rs.getRspcode()+":"+rs.getRspMsg());         logger.info("RESPONSE [POST] "+ getURI()+ "[CACHE] [RS_MSG]:"+rs.getRspcode()+":"+rs.getRspMsg());         return rs;      }   }      //DO REMOTE CALL   rs = gjjApiService.callGjjCenterCheckMpAndConvert(rq);   // 重新写缓存   cacheService.writeCache(rs, rq);      writeServerAccessLog(getURI(),"POST","ONRESPONSE","RESPONSE:"+rs.getRspcode()+":"+rs.getRspMsg());   logger.info("RESPONSE [POST] "+ getURI()+ " [RS_MSG]:"+rs.getRspcode()+":"+rs.getRspMsg());   return rs;}/** * controller主方法 GET *  * @return */@RequestMapping(value = "/gjjmp/{payCityID}_{idno}_{name}", method = RequestMethod.GET)public IcsGjjMpCrResponse getGjjMpCr(@PathVariable String payCityID, @PathVariable String idno, @PathVariable String name){   logger.info(System.getProperty("user.home"));   IcsGjjMpCrResponse rs = null;   ISwitchService gjjApiService = serviceMap.get("checkMpRouting");   IcsGjjMpCrRequest rq = new IcsGjjMpCrRequest();   rq.setPayCityID(payCityID);   rq.setIdno(idno);   rq.setName(name);   rq.setUuid(bean.getUuid());   rq.setLocalServerInfo(bean.getLocalHost());      String rqStr = DataConvert.toJson(rq);   logger.info("REQUEST [GET] "+ getURI());   writeServerAccessLog(getURI(),"GET","ONCALL", rqStr);   //DO REMOTE CALL   rs = gjjApiService.callGjjCenterCheckMpAndConvert(rq);      // 重新写缓存   cacheService.writeCache(rs, rq);   writeServerAccessLog(getURI() ,"GET","ONRESPONSE","RESPONSE:"+rs.getRspcode()+":"+rs.getRspMsg());   logger.info("RESPONSE [GET] [uri]:"+getURI() +" [RS_MSG]:" +rs.getRspcode()+":"+rs.getRspMsg()) ;   return rs;}
反欺诈调用方代码
/*** public PYFQZPojo pojo = new PYFQZPojo();    System.<span lang="EN-US" style="" font-size:"="">out.println("开始调用鹏元反欺诈接口---------------------------------------------------------------------------------");    out.println(pyfqz_Url);    JSONObject fraudRiskInfo=null,personRiskAssess=null;    默认赋值未String zxCount="0",swCount="0",sxCount="0",wdyqCount="0",alCount="0",cqggCount="0";    if"".equals(interfaceResult)){        // 调用失败        pojo.setMessage("{\"ret\":false,\"errorMsg\":\"接口调用失败,请核查连接信息"+pyfqz_Url+"\"}");    else{        JSONObject object = JSONObject.parseObject(interfaceResult);        Boolean  ret = (Boolean) object.get("ret");        if(!ret || (object.containsKey("errorMsg") && !"".equals(object.getString("errorMsg")))){            pojo.setMessage(object.toString());        }else{// 调用成功            JSONObject data = (JSONObject) object.get("data");            JSONObject reportElement = (JSONObject) ((JSONObject) data.get("cisReportChild")).get("reportElement");           //是否命中欺诈风险名单 "state":"是否命中欺诈风险名单,取值:0/10表示未命中欺诈风险名单,1表示命中欺诈风险名单"            if(reportElement.containsKey("fraudRiskInfo")){                if(reportElement.containsKey("treatResult")){                    if("1".equals(reportElement.get("treatResult"))){//直接从鹏元查数据                        fraudRiskInfo =  (JSONObject) reportElement.get("fraudRiskInfo");                    }else{                       pojo.setMessage("{\"ret\":false,\"errorMsg\":\"来自鹏元无此节点值\"}");                        return pojo;                    }                }else { // 直接从外联库中取                    fraudRiskInfo =  (JSONObject) reportElement.get("fraudRiskInfo");                }            }           //是否命中高风险名单 "checkResult":"是否命中高风险名单  1:是,2:否"            if(reportElement.containsKey("personRiskAssess")){                if(reportElement.containsKey("treatResult")){                    if("1".equals(reportElement.get("treatResult"))){//直接从鹏元查数据                        personRiskAssess =  (JSONObject) reportElement.get("personRiskAssess");                    }else{                       pojo.setMessage("{\"ret\":false,\"errorMsg\":\"来自鹏元无此节点值\"}");                        return pojo;                    }                }else { // 直接从外联库中取                    personRiskAssess =  (JSONObject) reportElement.get("personRiskAssess");                }            }            //风险信息            JSONObject personRiskInfo= null;            if(reportElement.containsKey("personRiskInfo")){                if(reportElement.containsKey("treatResult")){                    if("1".equals(reportElement.get("treatResult"))){//直接从鹏元查数据                        personRiskInfo =  (JSONObject) reportElement.get("personRiskInfo");                    }else{                       pojo.setMessage("{\"ret\":false,\"errorMsg\":\"来自鹏元无此节点值\"}");                        return pojo;                    }                }else { // 直接从外联库中取                    personRiskInfo =  (JSONObject) reportElement.get("personRiskInfo");                }            }            zxCount = String.valueOf(personRiskInfo.get("zxCount"));            swCount = String.valueOf(personRiskInfo.get("swCount"));            sxCount = String.valueOf(personRiskInfo.get("sxCount"));            wdyqCount = String.valueOf(personRiskInfo.get("wdyqCount"));            alCount = String.valueOf(personRiskInfo.get("alCount"));            cqggCount = String.valueOf(personRiskInfo.get("cqggCount"));            pojo = JSONObject.toJavaObject(personRiskInfo,PYFQZPojo.class);            pojo.setPersonRiskAssess(personRiskAssess.toString());            pojo.setFraudRiskInfo(fraudRiskInfo.toString());            pojo.setMessage( "{\"ret\":true}");            return pojo;        }    }    pojo;<span lang="EN-US" font-size:10.5pt;font-family:consolas;"="">}

原创粉丝点击