http响应结果包装工具类封装(开箱即用,无需依赖)

  • HttpEnum
package com.lenovo.lps.cost.integrator.utils.http;

import lombok.Getter;

/**
 * http response enum
 */
public enum HttpEnum {

    SUCCESS(200, "success"), ERROR(500, "fail");
    /**
     * 状态码
     */
    @Getter
    private int code;
    /**
     * 备注
     */
    @Getter
    private String remark;

    HttpEnum(int code, String remark) {
        this.code = code;
        this.remark = remark;
    }


}

ApiResponse

package com.lenovo.lps.cost.integrator.utils.http;


/**
 * http统一响应封装
 */
public class ApiResponse {
    /**
     * 状态码
     */
    private int code;
    /**
     * 数据
     */
    private Object data;
    /**
     * 报文描述
     */
    private String message;

    public ApiResponse(int code, Object data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    private ApiResponse(int code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 无参空构造
     */
    private ApiResponse() {
    }


    /**
     * 成功
     *
     * @param data 数据
     * @return
     */
    public static ApiResponse success(Object data) {
        return new ApiResponse(HttpEnum.SUCCESS.getCode(), data, HttpEnum.SUCCESS.getRemark());
    }

    /**
     * 成功
     *
     * @return
     */
    public static ApiResponse success() {
        return new ApiResponse(HttpEnum.SUCCESS.getCode(), HttpEnum.SUCCESS.getRemark());
    }


    /**
     * 失败
     *
     * @return
     */
    public static ApiResponse error() {
        return new ApiResponse(HttpEnum.ERROR.getCode(), HttpEnum.ERROR.getRemark());
    }

    /**
     * 失败
     *
     * @param message 消息
     * @return
     */
    public static ApiResponse error(String message) {
        return new ApiResponse(HttpEnum.ERROR.getCode(), message);
    }

    public static ApiResponse error(int code,Object data,String message) {
        return new ApiResponse(code,data, message);
    }

    public int getCode() {
        return code;
    }

    public void setStatusCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

  • 使用

return ApiResponse.success();
return ApiResponse.success(xxxx);
return ApiResponse.error();
return ApiResponse.error(xxxx);
也可以自定义状态码

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知命巅峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值