如何写一个JAVA后端接口:
接口通用
1.封装发送请求的方法:
public String doPost(String url,String json, String[] headers) {
Request.Builder builder = new Request.Builder();
if (headers != null && headers.length > 0) {
if (headers.length % 2 == 0) {
for (int i = 0; i < headers.length; i = i + 2) {
builder.addHeader(headers[i], headers[i + 1]);
}
} else {
log.warn("headers's length[{}] is error.", headers.length);
}
}
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = builder.url(url).post(requestBody).build();
return execute(request);
}
public String doGet(String url, Map<String, String> params, String[] headers) {
StringBuilder sb = new StringBuilder(url);
if (params != null && params.keySet().size() > 0) {
boolean firstFlag = true;
for (String key : params.keySet()) {
if (firstFlag) {
sb.append("?").append(key).append("=").append(params.get(key));
firstFlag = false;
} else {
sb.append("&").append(key).append("=").append(params.get(key));
}
}
}
Request.Builder builder = new Request.Builder();
if (headers != null && headers.length > 0) {
if (headers.length % 2 == 0) {
for (int i = 0; i < headers.length; i = i + 2) {
builder.addHeader(headers[i], headers[i + 1]);
}
} else {
log.warn("headers's length[{}] is error.", headers.length);
}
}
Request request = builder.url(sb.toString()).build();
log.info("do get request and url[{}]", sb.toString());
return execute(request);
}
// 发送请求
private String execute(Request request) {
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return "";
}
2.在控制层中(controller)写接口的方法体:
@Operation(summary = "同步铁路接口", description = "同步铁路接口")
@PostMapping(value = "/railway/synchronization",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseResult> synRailway(
@RequestBody RailwaySynReq request,
@Parameter(description = "接口认证秘钥",example = "dsECbPi5SxHcCGlgl4CaOQrortjT6YTS") @RequestHeader(value = "Api-Key") String apiKey) {
String[] headers = {"Api-Key",apiKey};
String s = okHttpCli.doPost(host + "/v1/railway/synchronization", JSON.toJSONString(request), headers);
return ResponseEntity.ok( JSON.parseObject(s, ResponseResult.class));
}
3.在模型层(model)中写接口对象
@Data
@Schema(description = "同步铁路对象")
public class RailwaySynReq {
@Schema(description = "操作行为 1:创建对象 2:编辑对象 3:删除对象", title = "操作行为", example = "1")
private Integer operate;
@Schema(description = "操作对象ID", title = "操作对象ID",example = "CT106701")
private String operateID;
@Schema(description = "生产系统大项目ID", title = "生产系统大项目ID",example = "CT106701")
private String railwayID;
@Schema(description = "铁路名称", title = "铁路名称", example = "乐清港铁路支线")
private String railwayName;
@Schema(description = "项目类型 1:铁路 2:非铁路", title = "项目类型", example = "1")
private Integer kind;
@Schema(description = "编码", title = "编码", defaultValue = "CSHFE501KD01")
private String code;
}
4.写一个响应的结果类
@Getter
@Setter
@Schema(description = "请求响应结果")
public class ResponseResult {
@Schema(description = "当前时间", title = "当前时间")
private Long at;
@Schema(description = "响应状态码", title = "响应状态码")
private Integer code;
@Schema(description = "结果", title = "结果")
private String msg;
@Schema(description = "结果", title = "结果")
private Object result;
public ResponseResult(){
this.at = System.currentTimeMillis() / 1000;
this.code = 200;
this.msg = "成功";
}
public ResponseResult(Integer code,String msg){
this.at = System.currentTimeMillis() / 1000;
this.code = code == null ? 200 : code;
this.msg = msg == null ? "成功" : msg;
}
}