开发技巧 代码结构 常用代码范例 工具类 统一响应结构 响应结构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class ScResult<T> private constructor( private val code: Int, private val message: String, private val data: T? ) { private constructor(enum: ScResultEnum, data: T? = null) : this( enum.code, enum.message, data ) companion object { fun <T> ok(data: T? = null): ScResult<T> { return ScResult(ScResultEnum.OK, data) } fun <T> error(data: T? = null): ScResult<T> { return ScResult(ScResultEnum.INTERNAL_SERVER_ERROR, data) } fun <T> make(enum: ScResultEnum, data: T? = null): ScResult<T> { return ScResult(enum, data) } fun <T> make(code: Int, message: String, data: T? = null): ScResult<T> { return ScResult(code, message, data) } } override fun toString(): String { return "ScResult(code=$code, message='$message', data=$data)" } } 响应枚举 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 enum class ScResultEnum(val code: Int, val message: String) { OK(200, "Success"), // 请求成功 CREATED(201, "Created"), // 请求成功并且创建了新的资源 ACCEPTED(202, "Accepted"), // 请求已接受,但尚未处理 NO_CONTENT(204, "No Content"), // 请求成功,但没有返回内容 MOVED_PERMANENTLY(301, "Moved Permanently"), // 资源已永久移动到新位置 FOUND(302, "Found"), // 资源临时移动到新位置 SEE_OTHER(303, "See Other"), // 重定向到另一个 URI NOT_MODIFIED(304, "Not Modified"), // 资源未被修改 BAD_REQUEST(400, "Bad Request"), // 请求无效或格式错误 UNAUTHORIZED(401, "Unauthorized"), // 需要身份验证 FORBIDDEN(403, "Forbidden"), // 服务器拒绝请求 NOT_FOUND(404, "Not Found"), // 资源未找到 METHOD_NOT_ALLOWED(405, "Method Not Allowed"), // 请求方法不允许 NOT_ACCEPTABLE(406, "Not Acceptable"), // 服务器无法生成请求的内容 PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"), // 需要代理身份验证 REQUEST_TIMEOUT(408, "Request Timeout"), // 请求超时 CONFLICT(409, "Conflict"), // 请求冲突 GONE(410, "Gone"), // 资源已永久删除 LENGTH_REQUIRED(411, "Length Required"), // 需要 Content-Length 头 PRECONDITION_FAILED(412, "Precondition Failed"), // 预条件失败 PAYLOAD_TOO_LARGE(413, "Payload Too Large"), // 请求体过大 URI_TOO_LONG(414, "URI Too Long"), // URI 过长 UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"), // 媒体类型不受支持 RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable"), // 请求范围不可满足 EXPECTATION_FAILED(417, "Expectation Failed"), // 期望值失败 IM_A_TEAPOT(418, "I'm a teapot"), // 只为趣味性,表示服务器是茶壶 UPGRADE_REQUIRED(426, "Upgrade Required"), // 需要升级协议 INTERNAL_SERVER_ERROR(500, "Internal Server Error"), // 服务器内部错误 NOT_IMPLEMENTED(501, "Not Implemented"), // 服务器不支持请求的方法 BAD_GATEWAY(502, "Bad Gateway"), // 网关或代理服务器收到无效响应 SERVICE_UNAVAILABLE(503, "Service Unavailable"), // 服务不可用 GATEWAY_TIMEOUT(504, "Gateway Timeout"), // 网关或代理服务器超时 HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"), // HTTP 版本不受支持 NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required"); // 需要网络认证 }