一个简单的retrofit工具类

使用

// 同步返回Optional<T>
var repos = RetrofitUtils.execute(service.listRepos("octocat")).orElse(new ArrayList<>());
// 异步
RetrofitUtils.execute(service.listRepos("octocat"), repos -> {
  //业务逻辑
});

源码

最新请到gist.github.com/jiangtj

package com.jiangtj.utils;

import lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * Created by MrTT (jiang.taojie@foxmail.com)
 * 2019/9/5.
 */
@Slf4j
public class RetrofitUtils {

    public static <T> Optional<T> execute(Call<T> call) {
        T object = null;
        try {
            Response<T> response = call.execute();
            if (response.isSuccessful()) {
                object = response.body();
            } else {
                log.error("RetrofitUtils execute fail code:{} errorBody:{}", response.code(), response.errorBody().string());
            }
        } catch (IOException e) {
            log.error("RetrofitUtils IOException:", e);
        }
        return Optional.ofNullable(object);
    }

    public static <T> void execute(Call<T> call, Consumer<T> success) {
        execute(call, success, throwable -> log.error("RetrofitUtils onFailure:", throwable));
    }

    public static <T> void execute(Call<T> call, Consumer<T> success, Consumer<Throwable> fail) {
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.isSuccessful()) {
                    success.accept(response.body());
                } else {
                    try {
                        log.error("RetrofitUtils execute fail code:{} errorBody:{}", response.code(), response.errorBody().string());
                    } catch (IOException e) {
                        log.error("RetrofitUtils IOException:", e);
                    }
                }
            }
            @Override
            public void onFailure(Call<T> call, Throwable throwable) {
                fail.accept(throwable);
            }
        });
    }

}
本文作者: Mr.J
本文链接: dnocm.com/articles/beec
版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
编辑于 2019-09-06