什么是接口
接口无非就是客户端请求你的接口地址,并传入一堆该接口定义好的参数,通过接口自身的逻辑处理,返回接口约定好的数据以及相应的数据格式。
接口怎么开发
接口由于本身的性质,由于和合作方对接数据,所以有以下几点需要在开发的时候注意:
1、定义接口入参:写好接口文档
2、定义接口返回数据类型:一般都需要封装成一定格式,确定返回json还是xml报文等
见如下返回数据定义格式:
package com.caiex.vb.model;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Result", propOrder = { "resultCode", "resultMsg" })
public class Result implements Serializable {
private static final long serialVersionUID = 10L;
protected int resultCode;
protected String resultMsg;
public int getResultCode() {
return this.resultCode;
}
public void setResultCode(int value) {
this.resultCode = value;
}
public String getResultMsg() {
return this.resultMsg;
}
public void setResultMsg(String value) {
this.resultMsg = value;
}
}
package com.caiex.vb.model;
import java.io.Serializable;
public class Response implements Serializable {
private static final long serialVersionUID = 2360867989280235575L;
private Result result;
private Object data;
public Result getResult() {
if (this.result == null) {
this.result = new Result();
}
return result;
}
public void setResult(Result result) {
this.result = result;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
3、确定访问接口的方式,get or post等等,可以根据restful接口定义规则RESTful API。
4、定义一套全局统一并通用的返回码,以帮助排查问题;
public static int NO_AGENT_RATE = 1119; //未找到兑换率
public static int SCHEME_COMMIT_FAIL = 4000; //方案提交失败
public static int SCHEME_CONFIRMATION = 4001; //方案确认中
public static int SCHEME_NOT_EXIST = 4002; //方案不存在
public static int SCHEME_CANCEL= 4005; //方案不存在
//。。。。
5、统一的异常处理:应该每个系统都需要一套统一的异常处理
package com.caiex.vb.interceptor;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.caiex.vb.model.Response;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 所有异常报错
* @param request
* @param exception
* @return
* @throws Exception
*/
@ExceptionHandler(value=Exception.class)
public Response allExceptionHandler(HttpServletReques