Kotlin 协程(Coroutines)配合使用 Retrofit,网络请求

本文介绍了如何在Android中结合Kotlin协程和Retrofit进行网络请求的实现,包括添加依赖、设置数据回调、配置Retrofit对象、处理网络请求的生命周期,以及封装网络请求接口。同时,提到了超时、缓存、Cookie管理和自定义异常处理。提供了源码参考链接。
摘要由CSDN通过智能技术生成

第一步 :添加所需依赖 

  //管理生命周期
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
    //添加支持Kotlin协程
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"
    //添加Retrofit网络请求依赖
    implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    //添加OKhttp相关依赖 可以用来配置其他配置属性
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.11.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.blankj:utilcode:1.28.1'

第二步 : 这里使用了 Kotlin的 DSL 语法创建了一个 数据返回回调监听

class RetrofitCoroutineDSL<T> {

    internal var onSuccess : ((T) -> Unit)? = null
        private set
    internal var onFail: ((exception: RequestResultException) -> Unit)? = null
        private set
    internal var onComplete : (() -> Unit)? = null
        private set

    fun onSuccess(block : (T) -> Unit){
        this.onSuccess = block
    }

    fun onFail(block: (exception: RequestResultException) -> Unit) {
        this.onFail = block
    }

    fun onComplete(block : () -> Unit){
        this.onComplete = block
    }

    internal fun clean(){
        onSuccess = null
        onComplete = null
        onFail = null
    }
}

这里面包含了 自定义的异常处理(RequestResultException)

public class RequestResultException extends Exception{

    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;
    private static final int CONTENT_IS_TOO_LARGE = 413;

    private HttpResult result;
    private String errorMessage;
    private String errorType;
    private Throwable throwable;

    public RequestResultException(@NotNull Throwable throwable) {
        throwable.printStackTrace();
        this.throwable = throwable;
        if (throwable instanceof HttpException){
            switch (((HttpException) throwable).code()){
                case CONTENT_IS_TOO_LARGE:
                    errorMessage = "内容过大:"+((HttpException) throwable).code();
                    break;
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    errorMessage = "网络错误:"+((HttpException) throwable).code();
                    break;
            }
            try {
                ResponseBody responseBody = ((HttpException) throwable).response().errorBody();
                if (responseBody != null){
                    String errorMsg = new String(responseBody.bytes());
                    if (!TextUtils.isEmpty(errorMsg)){
                        result = GsonUtils.fromJson(errorMsg, HttpResult.class);
                        errorMessage = result.getMessage();
                        errorType = result.getMessageType();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (throwable instanceof JsonParseException
                || throwable instanceof JSONException
                || throwable instanceof ParseException){
            errorMessage = "解析错误";
        }else if (throwable instanceof ConnectException) {
            errorMessage = "连接失败";
        }else if (throwable instanceof SocketTimeoutException){
            errorMessage = "连接超时";
        }else if (throwable instanceof SocketException){
            errorMessage = "连接关闭";
        }else if (throwable instanceof javax.net.ssl.SSLHandshakeException) {
            errorMessage = "证书验证失败";
        }else if (throwable instanceof ResponseMessageException) {
            result = ((ResponseMessageException) throwable).response();
            errorMessage = ((ResponseMessageException) throwable).errorMessage();
            errorType = ((ResponseMessageException) throwable).errorType();
        }else {
            try {
//                errorMessage = "未知错误:"+throwable.getMessage();
                errorMessage = "";
                /*Log.e("未知错误",throwable.getMessage());
                throwable.printStackTrace();*/
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public String getErrorType() {
        return errorType;
    }

    public HttpResult getResult() {
        return result;
    }

    public String getErrorCode(){
        return result != null ? (TextUtils.isEmpty(result.getErrorCode()) ? "" : result.getErrorCode()) : "";
    }

    public Throwable getThrowable() {
        return throwable;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

WL-鬼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值