Retrofit+LiveData实现网络请求(Java版本)

搜了好多相关文章,但是发现貌似都是基于官方Demo中的例子实现的。于是照猫画虎实现了Java版本。

其实其中的心就是自定义CallAdapter实现对请求结果的基础处理以及转换。

下面开始正文:

正文

  • 引入Retrofit
dependencies {
   ...

    //retrofit
    api 'com.squareup.retrofit2:retrofit:2.8.1'
    api 'com.squareup.okhttp3:okhttp:4.5.0'
    api 'com.squareup.retrofit2:converter-gson:2.5.0'
    api 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
}
  • 自定义一个请求结果的泛型ApiResponse
public class ApiResponse<T> {

    public static final int CODE_SUCCESS = 0;
    public static final int CODE_ERROR = 1;

    public int code; //状态码
    public String msg; //信息
    public T data; //数据

    public ApiResponse(int code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }

    public ApiResponse(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
}
  • 自定义 LiveDataCallAdapter
public class LiveDataCallAdapter<T> implements CallAdapter<T, LiveData<T>> {

    private Type mResponseType;
    private boolean isApiResponse;

    LiveDataCallAdapter(Type mResponseType, boolean isApiResponse) {
        this.mResponseType = mResponseType;
        this.isApiResponse = isApiResponse;
    }

    @NotNull
    @Override
    public Type responseType() {
        return mResponseType;
    }

    @NotNull
    @Override
    public LiveData<T> adapt(@NotNull final Call<T> call) {
        return new MyLiveData<>(call, isApiResponse);
    }

    private static class MyLiveData<T> extends LiveData<T> {

        private AtomicBoolean stared = new AtomicBoolean(false);
        private final Call<T> call;
        private boolean isApiResponse;

        MyLiveData(Call<T> call, boolean isApiResponse) {
            this.call = call;
            this.isApiResponse = isApiResponse;
        }

        @Override
        protected void onActive() {
            super.onActive();
            //确保执行一次
            if (stared.compareAndSet(false, true)) {
                call.enqueue(new Callback<T>() {
                    @Override
                    public void onResponse(@NotNull Call<T> call, @NotNull Response<T> response) {
                        T body = response.body();
                        postValue(body);
                    }

                    @Override
                    public void onFailure(@NotNull Call<T> call, @NotNull Throwable t) {
                        if (isApiResponse) {
                            //noinspection unchecked
                            postValue((T) new ApiResponse<>(ApiResponse.CODE_ERROR, t.getMessage()));
                        } else {
                            postValue(null);
                        }
                    }
                });
            }
        }
    }
}

  • 自定义 LiveDataCallAdapterFactory
public class LiveDataCallAdapterFactory extends CallAdapter.Factory {

    private static final String TAG = LiveDataCallAdapterFactory.class.getSimpleName();

    @SuppressWarnings("ClassGetClass")
    @Nullable
    @Override
    public CallAdapter<?, ?> get(@NotNull Type returnType, @NotNull Annotation[] annotations, @NotNull Retrofit retrofit) {
        if (getRawType(returnType) != LiveData.class) {
            return null;
        }
        //获取第一个泛型类型
        Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
        Class<?> rawType = getRawType(observableType);
        Log.d(TAG, "rawType = " + rawType.getClass().getSimpleName());
        boolean isApiResponse = true;
        if (rawType != ApiResponse.class) {
            //不是返回ApiResponse类型的返回值
            isApiResponse = false;
        }
        if (observableType instanceof ParameterizedType) {
            throw new IllegalArgumentException("resource must be parameterized");
        }
        return new LiveDataCallAdapter<>(observableType, isApiResponse);
    }
}

两个核心类就完成了。

  • 自定义Retrofit管理类RetrofitManager
public class RetrofitManager {

    //服务器请求baseUrl
    private static String sBaseUrl = null;

    //超时时长 默认10s
    private static int sConnectTimeout = 10;

    //用于存储retrofit
    private static ConcurrentHashMap<String, Retrofit> sRetrofitMap;

    private static OkHttpClient.Builder sOkHttpBuilder;

    //用于日期转换
    private static Gson sDataFormat;

    static {
        sRetrofitMap = new ConcurrentHashMap<>();

        sOkHttpBuilder = new OkHttpClient.Builder();
        //超时时长
        sOkHttpBuilder.connectTimeout(sConnectTimeout, TimeUnit.SECONDS);

        sDataFormat = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
    }

    //初始化主要的baseUrl  便于后期直接获取
    public static void init(String baseUrl) {
        sBaseUrl = baseUrl;
    }

    public static String getsBaseUrl() {
        return sBaseUrl;
    }

    public static void setConnectTimeout(int connectTimeout) {
        sConnectTimeout = connectTimeout;
    }

    public static Retrofit get() {
        Retrofit retrofit = sRetrofitMap.get(sBaseUrl);
        if (retrofit == null) {
            throw new RuntimeException("BASE_URL为空");
        }
        return retrofit;
    }

    public static Retrofit get(String baseUrl) {
        Retrofit retrofit = sRetrofitMap.get(baseUrl);
        if (retrofit == null) {
            retrofit = createRetrofit(baseUrl);
            sRetrofitMap.put(baseUrl, retrofit);
        }
        return retrofit;
    }

    /**
     * 创建Retrofit对象
     *
     * @param baseUrl baseUrl
     * @return Retrofit
     */
    private static Retrofit createRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(sOkHttpBuilder.build())
                .addCallAdapterFactory(new LiveDataCallAdapterFactory())
                .addConverterFactory(GsonConverterFactory.create(sDataFormat))
                .build();
    }
}

  • 最后再定义一个结果类和Service,这里以请求Bing的每日一图为例
public class BingImg {

    //bing每日一图:https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1
    public static final String REQUEST_URL = "https://cn.bing.com/";

    private static final String BASE_IMAGE_URL = "https://www.bing.com/";

    /**
     * images : [{"startdate":"20200413","fullstartdate":"202004131600","enddate":"20200414","url":"/th?id=OHR.BWFlipper_ZH-CN1813139386_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp","urlbase":"/th?id=OHR.BWFlipper_ZH-CN1813139386","copyright":"伊斯塔帕海岸的热带斑海豚,墨西哥 (© Christian Vizl/Tandem Stills + Motion)","copyrightlink":"https://www.bing.com/search?q=%E7%83%AD%E5%B8%A6%E6%96%91%E6%B5%B7%E8%B1%9A&form=hpcapt&mkt=zh-cn","title":"","quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20200413_BWFlipper%22&FORM=HPQUIZ","wp":true,"hsh":"b8381f6da75ae67b3581c0ca162718ac","drk":1,"top":1,"bot":1,"hs":[]}]
     * tooltips : {"loading":"正在加载...","previous":"上一个图像","next":"下一个图像","walle":"此图片不能下载用作壁纸。","walls":"下载今日美图。仅限用作桌面壁纸。"}
     */

    public TooltipsBean tooltips;
    public List<ImagesBean> images;

    public static class TooltipsBean {
        /**
         * loading : 正在加载...
         * previous : 上一个图像
         * next : 下一个图像
         * walle : 此图片不能下载用作壁纸。
         * walls : 下载今日美图。仅限用作桌面壁纸。
         */

        public String loading;
        public String previous;
        public String next;
        public String walle;
        public String walls;
    }

    public static class ImagesBean {
        /**
         * startdate : 20200413
         * fullstartdate : 202004131600
         * enddate : 20200414
         * url : /th?id=OHR.BWFlipper_ZH-CN1813139386_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
         * urlbase : /th?id=OHR.BWFlipper_ZH-CN1813139386
         * copyright : 伊斯塔帕海岸的热带斑海豚,墨西哥 (© Christian Vizl/Tandem Stills + Motion)
         * copyrightlink : https://www.bing.com/search?q=%E7%83%AD%E5%B8%A6%E6%96%91%E6%B5%B7%E8%B1%9A&form=hpcapt&mkt=zh-cn
         * title :
         * quiz : /search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20200413_BWFlipper%22&FORM=HPQUIZ
         * wp : true
         * hsh : b8381f6da75ae67b3581c0ca162718ac
         * drk : 1
         * top : 1
         * bot : 1
         * hs : []
         */

        public String startdate;
        public String fullstartdate;
        public String enddate;
        public String url;
        public String urlbase;
        public String copyright;
        public String copyrightlink;
        public String title;
        public String quiz;
        public boolean wp;
        public String hsh;
        public int drk;
        public int top;
        public int bot;
        public List<?> hs;
    }

    /**
     * 获取每日一图的url
     *
     * @return url
     */
    public String getImgUrl() {
        if (images != null && images.size() >= 1) {
            return BASE_IMAGE_URL + images.get(0).url;
        }
        return null;
    }
}
public interface SplashService {

    @GET("HPImageArchive.aspx?format=js&idx=0&n=1")
    Call<BingImg> getBingImg();

    @GET("HPImageArchive.aspx?format=js&idx=0&n=1")
    LiveData<BingImg> getBingImgLiveData();
}

使用

RetrofitManager.get("https://cn.bing.com/")
        .create(SplashService.class)
        .getBingImgLiveData().observe(this, new Observer<BingImg>() {
    @Override
    public void onChanged(BingImg bingImg) {
        Log.d(TAG, "onChanged: 请求结果:"+new Gson().toJson(bingImg));
    }
});

Demo链接

参考文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容