后端接口模版

文章展示了如何在Java后端使用OkHttp库来封装POST和GET请求方法,包括设置请求头和处理响应。在控制器层,定义了一个铁路接口同步的例子,接收请求对象和APIKey。模型层中定义了请求对象类,而响应结果类则包含了状态信息和结果数据。
摘要由CSDN通过智能技术生成

如何写一个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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值