Android OKHttp与Retrofit与RXJava的使用

发布于:2023-01-20 ⋅ 阅读:(12) ⋅ 点赞:(0) ⋅ 评论:(0)

目录

OKHTTP

依赖:

OKHttp是什么

优势:

OKHttp与Retrofit结合使用

Retrofit简介

RXJava的使用

RxJAVA简介


OKHTTP

依赖:

//OKHTTP依赖
    implementation("com.squareup.okhttp3:okhttp:4.10.0")

//RXJava依赖
    //添加RxJava依赖
    implementation "io.reactivex.rxjava3:rxjava:3.0.0"
    //添加RxAndroid依赖,专门用于Android的Rx库
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'

//retrofit依赖
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

//glide依赖
    implementation "com.github.bumptech.glide:glide:4.12.0"



    
    

OKHttp是什么

        OKHttp是一个网络请求开源项目, Android 网络请求轻量级框架 , 支持文件上传与下载,支持 https

优势:

        使用 OKHttp 无需重写您程序中的网络代码。 OKHttp 实现了几乎 java.net.HttpURLConnection 一样的 API。如果您用了 Apache HttpClient ,则 OKHttp 也提供了一个对应的 OKHttp-apache 模块
示例:
        Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">


    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/vp_show"
        android:layout_width="match_parent"
        android:layout_height="220dp" />

    <ImageView
        android:id="@+id/image_show"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="fitXY"
        app:srcCompat="@drawable/ic_launcher_background" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Viewpager2模板

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:id="@+id/image_moban"
        android:layout_width="match_parent"
        android:layout_height="210dp"
        app:srcCompat="@drawable/ic_launcher_background" />
</LinearLayout>

RecyclerView模板

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="160dp">


    <ImageView
        android:id="@+id/image_pic"
        android:layout_width="145dp"
        android:layout_height="145dp"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18dp"
            android:text="TextView" />

        <TextView
            android:id="@+id/tv_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>


</LinearLayout>

Viewpager2实体类

package com.hp.day42start1.modo;

public class Lun {
    String image_moban;

    public Lun(String image_moban) {
        this.image_moban = image_moban;
    }

    public String getImage_moban() {
        return image_moban;
    }
}

RecyclerView实体类

package com.hp.day42start1.modo;

public class Pubu {
    String image_pic;
    String tv_title;
    String tv_desc;

    public Pubu(String image_pic, String tv_title, String tv_desc) {
        this.image_pic = image_pic;
        this.tv_title = tv_title;
        this.tv_desc = tv_desc;
    }

    public String getImage_pic() {
        return image_pic;
    }

    public String getTv_title() {
        return tv_title;
    }

    public String getTv_desc() {
        return tv_desc;
    }
}

Viewpager2适配器

package com.hp.day42start1.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hp.day42start1.R;
import com.hp.day42start1.modo.Lun;

import java.util.List;

public class LunAdapter extends RecyclerView.Adapter<LunAdapter.ViewHodel> {
    List<Lun> list;

    public LunAdapter(List<Lun> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHodel onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lun_item, parent, false);
        ViewHodel viewHodel = new ViewHodel(view);
        return viewHodel;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHodel holder, int position) {
        Lun lun = list.get(position);
        Glide.with(holder.view).load(lun.getImage_moban()).into(holder.image_moban);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHodel extends RecyclerView.ViewHolder {
        ImageView image_moban;
        View view;
        public ViewHodel(@NonNull View itemView) {
            super(itemView);
            this.view=itemView;
            image_moban=itemView.findViewById(R.id.image_moban);
        }
    }
}

RecyclerView适配器

package com.hp.day42start1.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hp.day42start1.R;
import com.hp.day42start1.modo.Pubu;

import java.util.List;

public class PubuAdapter extends RecyclerView.Adapter<PubuAdapter.ViewHodel> {
    List<Pubu> list;

    public PubuAdapter(List<Pubu> list) {
        this.list = list;
    }

    @NonNull
    @Override
    public ViewHodel onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.pubu_item, parent, false);
        ViewHodel viewHodel = new ViewHodel(view);
        return viewHodel;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHodel holder, int position) {
        Pubu pubu = list.get(position);
        holder.tv_title.setText(pubu.getTv_title());
        holder.tv_desc.setText(pubu.getTv_desc());
        Glide.with(holder.view).load(pubu.getImage_pic()).into(holder.image_pic);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHodel extends RecyclerView.ViewHolder {
        ImageView image_pic;
        TextView tv_title,tv_desc;
        View view;
        public ViewHodel(@NonNull View itemView) {
            super(itemView);
            this.view=itemView;
            image_pic=itemView.findViewById(R.id.image_pic);
            tv_title=itemView.findViewById(R.id.tv_title);
            tv_desc=itemView.findViewById(R.id.tv_desc);
        }
    }
}

MainActivity.java

package com.hp.day42start1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.hp.day42start1.adapter.LunAdapter;
import com.hp.day42start1.adapter.PubuAdapter;
import com.hp.day42start1.modo.Lun;
import com.hp.day42start1.modo.Pubu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private ViewPager2 vp_show;
    private ImageView image_show;
    private RecyclerView rv_show;
    String resu="";
    List<Lun> list = new ArrayList<>();
    List<Pubu> lists = new ArrayList<>();
    boolean flag=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vp_show = findViewById(R.id.vp_show);
        image_show = findViewById(R.id.image_show);
        rv_show = findViewById(R.id.rv_show);

        into();
        init();
        initdate();

    }
    private void into(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.vvhan.com/api/hotlist?type=wxHot")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("=======", "错了,错了,真的错了,别异常了");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                resu=response.body().string();
                handler.sendEmptyMessage(0x111);
            }
        });
    }
    private void initdate(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.vvhan.com/api/hotlist?type=baiduRD")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("=======", "错了,错了,真的错了,别异常了");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                resu=response.body().string();
                handler.sendEmptyMessage(0x113);
                Log.i("=======", resu);
            }
        });
    }
    private void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request
                            .Builder()
                            .url("https://api.vvhan.com/api/view?type=json")
                            .build();
                    try (Response response = okHttpClient.newCall(request).execute()) {
                        resu = response.body().string();
                        handler.sendEmptyMessage(0x112);
                        Thread.sleep(10000);
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


//            okHttpClient.newCall(request).enqueue(new Callback() {
//                @Override
//                public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                    Log.i("=======", "错了,错了,真的错了,别异常了");
//                }
//
//                @Override
//                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                    resu = response.body().string();
//                    handler.sendEmptyMessage(0x112);
//                    try {
//                        Thread.sleep(15000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//               }
//            });
//        }
    }
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==0x111){
                try {
                    JSONObject jsonObject = new JSONObject(resu);
                    JSONArray data = jsonObject.getJSONArray("data");
                    if (data.length()<5){
                        for (int i = 0; i <data.length(); i++) {
                            JSONObject object = data.getJSONObject(i);
                            String pic = object.getString("pic");
                            Lun lun = new Lun(pic);
                            list.add(lun);
                        }
                    }else {
                        for (int i = 0; i <5; i++) {
                            JSONObject object = data.getJSONObject(i);
                            String pic = object.getString("pic");
                            Lun lun = new Lun(pic);
                            list.add(lun);
                        }
                    }
                    LunAdapter lunAdapter = new LunAdapter(list);
                    vp_show.setAdapter(lunAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (msg.what==0x112){
                try {
                    JSONObject jsonObject = new JSONObject(resu);
                    String imgurl = jsonObject.getString("imgurl");
                    Glide.with(MainActivity.this).load(imgurl).into(image_show);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (msg.what==0x113){
                try {
                    JSONObject jsonObject = new JSONObject(resu);
                    JSONArray data = jsonObject.getJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject object = data.getJSONObject(i);
                        String title = object.getString("title");
                        String desc = object.getString("desc");
                        String pic = object.getString("pic");
                        Pubu pubu = new Pubu(pic,title,desc);
                        Log.i("=======", title);
                        lists.add(pubu);
                    }
                    LinearLayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
                    PubuAdapter pubuAdapter = new PubuAdapter(lists);

                    rv_show.setLayoutManager(layoutManager);
                    rv_show.setAdapter(pubuAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        flag=false;
    }
}

OKHttp与Retrofit结合使用

Retrofit简介

        我们项目当中的每个app 都需要用到网络和服务器进行交互,在 Android 项目开发中使用 HTTP 协议完成 通信的话,基本上都要用到OkHttp 或者 Retrofit
Retrofit 是什么?
        准确来说,Retrofit 是一个 RESTful HTTP 网络请求框架的封装。
总结
        Retrofit主要负责应用层面的封装,就是说主要面向开发者,方便使用,比如请求参数,响应数据的处 理,错误处理等等。
        Retrofit封装了具体的请求,线程切换以及数据转换。
        网上一般都推荐RxJava+Retrofit+OkHttp 框架, Retrofit 负责请求的数据和请求的结果,使用接口的 方式呈现, OkHttp 负责请求的过程, RxJava 负责异步,各种线程之间的切换,用起来非常便利
示例:
        Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/vp_show"
        android:layout_width="match_parent"
        android:layout_height="230dp"
        />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_show"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Viewpager2模板

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgurl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        tools:srcCompat="@tools:sample/avatars" />
</RelativeLayout>

RecyclerView模板

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="160dp">


    <ImageView
        android:id="@+id/pic"
        android:layout_width="150dp"
        android:layout_height="155dp"
        android:layout_gravity="center"
        tools:srcCompat="@tools:sample/avatars" />
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
        <TextView
            android:id="@+id/desc"
            android:layout_marginTop="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>


</LinearLayout>

实体类(本案例实体类是共用的)

package com.hp.day44start2.mudo;

import java.util.Date;
import java.util.List;

public class News {
    boolean success;
    String title;
    String subtitle;
    String update_time;
    List<Data> data;

    public News(List<Data> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "News{" +
                "success=" + success +
                ", title='" + title + '\'' +
                ", subtitle='" + subtitle + '\'' +
                ", update_time=" + update_time +
                ", data=" + data +
                '}';
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public String getUpdate_time() {
        return update_time;
    }

    public List<Data> getData() {
        return data;
    }

    public void setData(List<Data> data) {
        this.data = data;
    }

    public static class Data{
        int index;
        String title;
        String desc;
        String pic;
        String hot;
        String url;
        String mobilUrl;

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public String getPic() {
            return pic;
        }

        public void setPic(String pic) {
            this.pic = pic;
        }

        public String getHot() {
            return hot;
        }

        public void setHot(String hot) {
            this.hot = hot;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getMobilUrl() {
            return mobilUrl;
        }

        public void setMobilUrl(String mobilUrl) {
            this.mobilUrl = mobilUrl;
        }
    }
}

Viewpager2适配器

package com.hp.day44start2.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hp.day44start2.R;
import com.hp.day44start2.mudo.News;

public class LunAdapter extends RecyclerView.Adapter<LunAdapter.ViewHodel> {

    News viewPager2;

    public LunAdapter(News viewPager2) {
        this.viewPager2 = viewPager2;
    }

    @NonNull
    @Override
    public ViewHodel onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lun_item, parent, false);
        ViewHodel viewHodel = new ViewHodel(view);
        return viewHodel;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHodel holder, int position) {
        News.Data data=viewPager2.getData().get(position);
        Glide.with(holder.view).load(data.getPic()).into(holder.pic);
    }

    @Override
    public int getItemCount() {
        return viewPager2.getData().size();
    }

    public class ViewHodel extends RecyclerView.ViewHolder {
        ImageView pic;
        View view;
        public ViewHodel(@NonNull View itemView) {
            super(itemView);
            this.view = itemView;
            pic = itemView.findViewById(R.id.imgurl);
        }
    }
}

RecyclerView适配器

package com.hp.day44start2.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hp.day44start2.R;
import com.hp.day44start2.mudo.News;

import java.util.List;

import retrofit2.Call;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHodel> {
    News news;

    public NewsAdapter(News news) {
        this.news = news;
    }

    @NonNull
    @Override
    public ViewHodel onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
        ViewHodel viewHodel = new ViewHodel(view);
        return viewHodel;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHodel holder, int position) {
        News.Data data=news.getData().get(position);
        holder.title.setText(data.getTitle());
        holder.desc.setText(data.getDesc());
        Glide.with(holder.view).load(data.getPic()).into(holder.pic);

    }

    @Override
    public int getItemCount() {
        return news.getData().size();
    }



    public class ViewHodel extends RecyclerView.ViewHolder {
        ImageView pic;
        TextView title,desc;
        View view;
        public ViewHodel(@NonNull View itemView) {
            super(itemView);
            this.view = itemView;
            pic = itemView.findViewById(R.id.pic);
            title = itemView.findViewById(R.id.title);
            desc = itemView.findViewById(R.id.desc);
        }
    }
}

Viewpager2接口

package com.hp.day44start2.dao;

import com.hp.day44start2.mudo.News;

import retrofit2.Call;
import retrofit2.http.GET;

public interface LunShow {
    @GET("api/hotlist?type=36Ke")
    Call<News> getcalls();
}

RecyclerView接口

package com.hp.day44start2.dao;

import com.hp.day44start2.mudo.News;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.Url;

/**
 * https://api.vvhan.com/api/hotlist?type=36Ke
 * https:
 * @Query("type") String title
 */
public interface NewsDao {
    @GET("api/hotlist")
    Call<News> getcall(@Query("type") String type);
}

MainActivity.java

package com.hp.day44start2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.util.Log;

import com.hp.day44start2.adapter.LunAdapter;
import com.hp.day44start2.adapter.NewsAdapter;
import com.hp.day44start2.dao.LunShow;
import com.hp.day44start2.dao.NewsDao;
import com.hp.day44start2.mudo.News;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private ViewPager2 vp_show;
    private RecyclerView rv_show;

    List<News> list = new ArrayList<>();
    NewsAdapter newsAdapter;
    private String url="https://api.vvhan.com/";
//    String title="36Ke";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vp_show = findViewById(R.id.vp_show);
        rv_show = findViewById(R.id.rv_show);


    xinwen();
    initdata();

    }

    private void xinwen() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        NewsDao newsDao = retrofit.create(NewsDao.class);
        Call<News> getcall = newsDao.getcall("36Ke");
        getcall.enqueue(new Callback<News>() {
            @Override
            public void onResponse(Call<News> call, Response<News> response) {
                News body = response.body();
                Log.i("==============", body.toString());
                News news=new News(body.getData());
                NewsAdapter adapter=new NewsAdapter(news);
                LinearLayoutManager layoutManager=new LinearLayoutManager(MainActivity.this);
                rv_show.setLayoutManager(layoutManager);
                rv_show.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<News> call, Throwable t) {
                Log.i("=================", "连接错误");
            }
        });
    }

    private void initdata() {

        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        LunShow lunShow = retrofit.create(LunShow.class);
        Call<News> call = lunShow.getcalls();
        call.enqueue(new Callback<News>() {
            @Override
            public void onResponse(Call<News> call, Response<News> response) {
                News body = response.body();
                Log.i("================", body.toString());
                News newsVp2=new News(body.getData());
                LunAdapter adapter=new LunAdapter(newsVp2);
                vp_show.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<News> call, Throwable t) {

            }
        });

    }

}

RXJava的使用

RxJAVA简介

响应式编程
        在介绍RxJava 前,我们先聊聊响应式编程。那么什么是响应式编程呢?响应式编程是一种基于异步数据 流概念的编程模式。数据流就像一条河:它可以被观测,被过滤,被操作,或者为新的消费者与另外一 条流合并为一条新的流。
        响应式编程的一个关键概念是事件。事件可以被等待,可以触发过程,也可以触发其它事件。事件是唯 一的以合适的方式将我们的现实世界映射到我们的软件中:如果屋里太热了我们就打开一扇窗户。同样 的,当我们的天气app从服务端获取到新的天气数据后,我们需要更新 app 上展示天气信息的 UI ;汽车上 的车道偏移系统探测到车辆偏移了正常路线就会提醒驾驶者纠正,就是是响应事件。 今天,响应式编程最通用的一个场景是UI :我们的移动 App 必须做出对网络调用、用户触摸输入和系统 弹框的响应。在这个世界上,软件之所以是事件驱动并响应的是因为现实生活也是如此。
什么是 RxJava
        RxJava 是一种响应式编程,来创建基于事件的异步操作库。基于事件流的链式调用、逻辑清晰简
洁。
        RxJava 我的理解是将事件从起点(上游)流向终点(下游),中间有很多卡片对数据进操作并传 递,每个卡片获取上一个卡片传递下来的结果然后对事件进行处理然后将结果传递给下一个卡片, 这样事件就从起点通过卡片一次次传递直到流向终点。
        我对它的定义是:RxJava 本质上是一个异步操作库,是一个能让你用极其简洁的逻辑去处理繁琐复杂任 务的异步事件库。
什么是观察者模式?
        举个栗子,Android View 的点击监听器的实现, View 是被观察者, OnClickListener 对象是观察者, Activity要如何知道 View 被点击了?那就是派一个 OnClickListener 对象,入驻 View ,与 View 达成一个订 阅关系,一旦View 被点击了,就通过 OnClickListener 对象的 OnClick 方法传达 Activity 。采用观察者模 式可以避免去轮询检查,节约有限的cpu 资源。
示例:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         />

</LinearLayout>

实体类

package com.hp.day44start3.muodo;

import java.util.List;

public class News {
    boolean success;
    String title;
    String subtitle;
    String update_time;
    List<Data> data;

    public News(List<Data> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "News{" +
                "success=" + success +
                ", title='" + title + '\'' +
                ", subtitle='" + subtitle + '\'' +
                ", update_time=" + update_time +
                ", data=" + data +
                '}';
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public String getUpdate_time() {
        return update_time;
    }

    public List<Data> getData() {
        return data;
    }

    public void setData(List<Data> data) {
        this.data = data;
    }

    public static class Data{
        int index;
        String title;
        String desc;
        String pic;
        String hot;
        String url;
        String mobilUrl;

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public String getPic() {
            return pic;
        }

        public void setPic(String pic) {
            this.pic = pic;
        }

        public String getHot() {
            return hot;
        }

        public void setHot(String hot) {
            this.hot = hot;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getMobilUrl() {
            return mobilUrl;
        }

        public void setMobilUrl(String mobilUrl) {
            this.mobilUrl = mobilUrl;
        }
    }
}

接口:

package com.hp.day44start3.dao;

import com.hp.day44start3.muodo.News;


import io.reactivex.Observable;
import retrofit2.Call;
import retrofit2.http.GET;

public interface News_inteface {
    @GET("api/hotlist?type=36Ke")
    Observable<News> getnews();
}

适配器:

package com.hp.day44start3.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.hp.day44start3.R;
import com.hp.day44start3.muodo.News;

import java.util.List;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHodel> {
        List<News.Data> list;
        public void setRecuess(List<News.Data> list){
                this.list=list;
                notifyDataSetChanged();
        }
        @NonNull
        @Override
        public ViewHodel onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
                ViewHodel viewHodel = new ViewHodel(view);
                return viewHodel;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHodel holder, int position) {
                News.Data news = list.get(position);
                Glide.with(holder.view).load(news.getPic()).into(holder.pic);
                holder.title.setText(news.getTitle());
                holder.desc.setText(news.getDesc());
        }

        @Override
        public int getItemCount() {
                return list == null ? 0 : list.size();
        }

        public class ViewHodel extends RecyclerView.ViewHolder {
                ImageView pic;
                TextView title,desc;
                View view;
                public ViewHodel(@NonNull View itemView) {
                        super(itemView);
                        this.view = itemView;
                        pic = itemView.findViewById(R.id.pic);
                        title = itemView.findViewById(R.id.title);
                        desc = itemView.findViewById(R.id.desc);
                }
        }
}

MainActivity.java

package com.hp.day44start3;


import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hp.day44start3.adapter.NewsAdapter;
import com.hp.day44start3.dao.News_inteface;
import com.hp.day44start3.muodo.News;


import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 io.reactivex.Observable
 io.reactivex.rxjava3.core.Observable
 io.reactivex.rxjava3.core.Scheduler
 io.reactivex.Scheduler
 */
public class MainActivity extends AppCompatActivity {
    RecyclerView rv_show;
    NewsAdapter newsAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv_show = findViewById(R.id.rv_show);

        newsAdapter = new NewsAdapter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        rv_show.setLayoutManager(layoutManager);
        rv_show.setAdapter(newsAdapter);

        intoday();
    }

    private void intoday() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.vvhan.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        News_inteface news_inteface = retrofit.create(News_inteface.class);
        Observable<News> observable = news_inteface.getnews();
        observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<News>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(News news) {
                newsAdapter.setRecuess(news.getData());
            }

            @Override
            public void onError(Throwable e) {
                Log.i("========", "靠北啦,我真的会谢");
            }

            @Override
            public void onComplete() {
                Log.i("TAG", "连接成功");
            }
        });
    }
//基础使用示例
    //Observable<Integer> observable= Observable.create(new ObservableOnSubscribe<Integer>() {
//            @Override
//            public void subscribe(@NonNull ObservableEmitter<Integer> emitter) {
//                emitter.onNext(1);
//                emitter.onNext(2);
//                emitter.onNext(3);
//                emitter.onComplete();
//            }
//        });
//         Observer<Integer> observer=new Observer<Integer>() {
//             @Override
//             public void onSubscribe(@NonNull Disposable d) {
//                 Log.d("TAG", "开始采用subscribe链接");
//             }
//
//             @Override
//             public void onNext(@NonNull Integer integer) {
//                 Log.i("TAG", "响应事件"+integer);
//             }
//
//             @Override
//             public void onError(@NonNull Throwable e) {
//                 Log.i("TAG", "靠北啦,又搞这些");
//             }
//
//             @Override
//             public void onComplete() {
//                 Log.i("TAG", "对onComplete()做出回应");
//             }
//
//         };
//         observable.subscribe(observer);
}