美文网首页Android网络 apache retrofit server
Retrofit+LiveData实现网络请求(Java版本)

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

作者: 12313凯皇 | 来源:发表于2020-04-14 17:30 被阅读0次

    搜了好多相关文章,但是发现貌似都是基于官方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链接

    参考文章

    相关文章

      网友评论

        本文标题:Retrofit+LiveData实现网络请求(Java版本)

        本文链接:https://www.haomeiwen.com/subject/xxwtvhtx.html