• 网络请求-Retrofit+OkHttp+RxJava


    用https://www.wanandroid.com/网站提供的api

    1、retrofit GET请求

    public interface WanAndroidApi {
        //总数据
        @GET("project/tree/json")    //https://www.wanandroid.com/project/tree/json
        Observable<ProjectBean> getProject();
        //item数据API
        @GET("project/list/{pageIndex}/json")   //https://www.wanandroid.com/project/list/1/json?cid=294
        Observable<ProjectItem> getProjectItem(@Path("pageIndex") int pageIndex, @Query("cid") int cid);//会自动拼接成?cid=294
    }

    2、bean数据Android Studio插件GsonForm生成,此处代码省略

    3、创建Retrofit函数

    public class HttpUtil {
        public static String BASE_URL = "https://www.wanandroid.com/";
    
        //BASE_URL可设置
        public static void setBaseUrl(String baseUrl) {
            BASE_URL = baseUrl;
        }
    
        //创建Retrofit的函数
        public static Retrofit createRetrofit(){
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            OkHttpClient okHttpClient = builder.addNetworkInterceptor(new StethoInterceptor())
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .build();
            return new Retrofit.Builder().baseUrl(BASE_URL).client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
    }

    4、使用

        WanAndroidApi api = HttpUtil.createRetrofit().create(WanAndroidApi.class);
    
        //线程切换封装,耗时操作在子线程完成,界面更新在主线程完成
        private final static <UD> ObservableTransformer<UD, UD> rxUD(){
            return new ObservableTransformer<UD, UD>(){
    
                @Override
                public @NonNull ObservableSource<UD> apply(@NonNull Observable<UD> upstream) {
                    return upstream.subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
                }
            };
        }
    
    /*   lambda表达式
        private final static <UD> ObservableTransformer<UD, UD> rxUD(){
            return upstream -> upstream.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    */
    
        public void getProjectAction(View view) {
    
            api.getProject().compose(rxUD())
                    .subscribe(projectBean -> {
                        Log.d(TAG, "getProjectAction: " + projectBean);
                    });
                    /*.subscribe(new Consumer<ProjectBean>() {
                        @Override
                        public void accept(ProjectBean projectBean) throws Throwable {
                            Log.d(TAG, "accept: " + projectBean);
                        }
                    });*/
    
    
        }
    
        public void getProjectListAction(View view){
            api.getProjectItem(1, 294).compose(rxUD()).subscribe(projectItem -> {
                Log.d(TAG, "getProjectListAction: " + projectItem);
            });
        }
    
        /**
         * 嵌套查询
         */
        public void antiShakeAction(){
            api.getProject().compose(rxUD()).subscribe(projectBean -> {
                for (ProjectBean.DataBean dataBean : projectBean.getData()) {
                    api.getProjectItem(1, dataBean.getId()).compose(rxUD()).subscribe(projectItem -> {
                        Log.d(TAG, "antiShakeAction: " + projectItem);
                    });
                }
            });
        }

    解决之前OkHttp请求数据后,Handler更新UI比较繁琐的问题

    附:

        public void rxJavaDownloadImageAction(View view){
            Observable.just(PATH)       //自己创建数据,并非Retrofit装载
                    .map(new Function<String, Bitmap>() {
                        @Override
                        public Bitmap apply(String s) throws Throwable {//网络请求图片
                            URL url = new URL(PATH);
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            httpURLConnection.setConnectTimeout(5000);
                            int responseCode = httpURLConnection.getResponseCode();
                            if (responseCode == HttpURLConnection.HTTP_OK){
                                InputStream inputStream = httpURLConnection.getInputStream();
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                return bitmap;
                            }
                            return null;
                        }
                    })
                    .compose(rxUD())
                    .subscribe(v -> {
                        imageView.setImageBitmap(v);
                    });
        }
            String[] strings = {"Anny", "Victor", "Model"};
    /*
            for (String string : strings) {
                Log.d(TAG, "onCreate: for string" + string);
            }
    */
    
            Observable.fromArray(strings).subscribe(string -> {
                Log.d(TAG, "onCreate: rxJava string" + string);
            });
    
        }
  • 相关阅读:
    jQ的工具类方法
    jq-ajax
    jq-ajax-get
    LOAD
    JQ的尺寸类
    JQ-DOM与元素的操作
    jQ-DOM属性的操作
    jQ的事件
    3位创业公司CEO亲述:200人的小公司,这么做数据管理就对了
    十二潜意识的智商
  • 原文地址:https://www.cnblogs.com/anny0920/p/12991299.html
Copyright © 2020-2023  润新知