• 网络请求-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);
            });
    
        }
  • 相关阅读:
    JPA拼接子查询语句
    List<String> 转json(存入数据库),json转回List<String>
    spring里restTemplate向目的URL发送post请求
    js里Date时间格式的常用转换-------(GMT转成yyyy-MM-dd)--------(根据日期获得星期几)
    zip解压的mysql安装步骤
    mysql_把符合条件的某列的多条数据合并为一条
    Spring boot全局捕获异常处理!
    spring boot 整合springmvc 各种请求?
    spring boot学习教程
    复选框读取数据,分割字符串转换成数组,显示复选框选中。
  • 原文地址:https://www.cnblogs.com/anny0920/p/12991299.html
Copyright © 2020-2023  润新知