Retrofit+get+表单+json+异常处理

538 阅读1分钟

1.api

object Const {
    //    const val BASE_URL = "http://***.***.***.***:**/auto/back/orderSale/"
    const val BASE_URL = "http://gank.io/api/"
//    const val BASE_URL = "http://***.***.***:***/*******/"

    //get
    interface ArticalApi {
        @GET("xiandu/category1/{path}")
        suspend fun category(
            @Path("path") category: String
        ): Artical
    }
    
    //表单
    interface OrderApi {
        @POST("PDA/pickOrderSaleListDetail.do")
        @FormUrlEncoded
        suspend fun pickOrderSaleListDetail(
            @Field("orderId") orderId: String,
            @Field("status") status: Int
        ): Order
    }
    
    //json
    interface StockApi {
        @POST("api/basic/stockList")
        suspend fun stockList(
            @Body empty: UpEmpty
        ): Stock
    }
}

2.异常处理类

object ExceptionHandle {
    private const val UNAUTHORIZED = 401
    private const val FORBIDDEN = 403
    private const val NOT_FOUND = 404
    private const val REQUEST_TIMEOUT = 408
    private const val INTERNAL_SERVER_ERROR = 500
    private const val BAD_GATEWAY = 502
    private const val SERVICE_UNAVAILABLE = 503
    private const val GATEWAY_TIMEOUT = 504
    fun handle(e: Throwable): ResponeThrowable {
        val ex: ResponeThrowable

        return when (e) {
            is HttpException -> {
                ex = ResponeThrowable(e)
                when (e.code()) {
                    UNAUTHORIZED, FORBIDDEN -> ex.message = "禁止访问"
                    NOT_FOUND -> ex.message = "找不到服务器"
                    REQUEST_TIMEOUT -> ex.message = "请求超时"
                    GATEWAY_TIMEOUT -> ex.message = "网关超时"
                    INTERNAL_SERVER_ERROR -> ex.message = "服务器错误"
                    BAD_GATEWAY -> ex.message = "网关错误"
                    SERVICE_UNAVAILABLE -> ex.message = "服务器无响应"
                    else -> ex.message = "网络错误"
                }
                ex
            }
            is ServerException -> {
                val resultException = e
                ex = ResponeThrowable(resultException)
                ex.message = resultException.message
                ex
            }
            is JsonParseException, is JSONException -> {
                ex = ResponeThrowable(e)
                ex.message = "解析错误"
                ex
            }
            is ConnectException -> {
                ex = ResponeThrowable(e)
                ex.message = "连接失败,请检查网络"
                ex
            }
            is SSLHandshakeException -> {
                ex = ResponeThrowable(e)
                ex.message = "证书验证失败"
                ex
            }
            is SocketTimeoutException -> { // 超时
                ex = ResponeThrowable(e)
                ex.message = "请求超时"
                ex
            }
            else -> {
                ex = ResponeThrowable(e)
                ex.message = "未知错误"
                ex
            }
        }
    }

    class ResponeThrowable(throwable: Throwable?) : Exception(throwable) {
        override var message: String? = null

    }

    //     ServerException发生后,将自动转换为ResponeThrowable返回
    internal class ServerException : RuntimeException() {
        override var message: String? = null
    }
}

3.使用

fun getinfo(): MutableLiveData<Artical> {
        //协程理解,可suspend,且不阻塞线程。轻量级线程
        Jobutil.scope.launch {
            try {
                val artical = RFUtil.rf.create(Const.ArticalApi::class.java)
                    .category("hahaha")
                info.value = artical
                Jobutil.io("nihao")
                delay(1000)
                Jobutil.io("ok")
                Log.i("result-->", "thread:${Thread.currentThread().name}")
            } catch (e: Exception) {
                error.value = ExceptionHandle.handle(e).message
            }
        }
        return info
    }