Retrofit的簡單使用

寫代碼思路流程:

//1.權限和依賴
//2.佈局文件
//3.生成實體bean類
//4.封裝工具類 Retrofit + RxJava + OkHttp
//5.搭建MVP架構
//6.創建適配器
//7.在Activity或者Fragment中進行加載佈局管理器和綁定適配器


效果圖:



a.添加聯網權限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

b.依賴:(帶libs的依賴需要自己導入jar包,也可以自己在網上搜直接添加)

compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.0.1'

compile 'com.squareup.retrofit2:retrofit:2.0.2'                  //Retrofit2庫文件
compile 'com.squareup.retrofit2:converter-gson:2.0.2'           //支持Gson解析
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'           //支持RxJava
compile 'com.jcodecraeer:xrecyclerview:1.3.2'
compile 'com.github.bumptech.glide:glide:3.7.0'


佈局文件:


activity_main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="com.ccm.mvpretrofitrxjava.activity.MainActivity">  
  8.   
  9.     <com.jcodecraeer.xrecyclerview.XRecyclerView  
  10.         android:id="@+id/xrv"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="match_parent"></com.jcodecraeer.xrecyclerview.XRecyclerView>  
  13.   
  14. </android.support.constraint.ConstraintLayout>  



recy_item
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="50dp"  
  5.     android:orientation="horizontal">  
  6.   
  7.     <ImageView  
  8.         android:id="@+id/iv_item"  
  9.         android:layout_width="50dp"  
  10.         android:layout_height="match_parent" />  
  11.   
  12.     <TextView  
  13.         android:id="@+id/tv_item"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="match_parent"  
  16.         android:text="我是文本"  
  17.         android:textSize="20sp"/>  
  18. </LinearLayout>  

生成實體bean類:

  1. public class Bean {  
  2.   
  3.     private String msg;  
  4.     private RetEntity ret;  
  5.     private String code;  
  6.   
  7.     public String getMsg() {  
  8.         return msg;  
  9.     }  
  10.   
  11.     public void setMsg(String msg) {  
  12.         this.msg = msg;  
  13.     }  
  14.   
  15.     public RetEntity getRet() {  
  16.         return ret;  
  17.     }  
  18.   
  19.     public void setRet(RetEntity ret) {  
  20.         this.ret = ret;  
  21.     }  
  22.   
  23.     public String getCode() {  
  24.         return code;  
  25.     }  
  26.   
  27.     public void setCode(String code) {  
  28.         this.code = code;  
  29.     }  
  30.   
  31.     public static class RetEntity {  
  32.           
  33.         private AdvEntity adv;  
  34.         private int pnum;  
  35.         private int totalRecords;  
  36.         private int records;  
  37.         private int totalPnum;  
  38.         private List<?> bannerList;  
  39.         private List<ListEntity> list;  
  40.   
  41.         public AdvEntity getAdv() {  
  42.             return adv;  
  43.         }  
  44.   
  45.         public void setAdv(AdvEntity adv) {  
  46.             this.adv = adv;  
  47.         }  
  48.   
  49.         public int getPnum() {  
  50.             return pnum;  
  51.         }  
  52.   
  53.         public void setPnum(int pnum) {  
  54.             this.pnum = pnum;  
  55.         }  
  56.   
  57.         public int getTotalRecords() {  
  58.             return totalRecords;  
  59.         }  
  60.   
  61.         public void setTotalRecords(int totalRecords) {  
  62.             this.totalRecords = totalRecords;  
  63.         }  
  64.   
  65.         public int getRecords() {  
  66.             return records;  
  67.         }  
  68.   
  69.         public void setRecords(int records) {  
  70.             this.records = records;  
  71.         }  
  72.   
  73.         public int getTotalPnum() {  
  74.             return totalPnum;  
  75.         }  
  76.   
  77.         public void setTotalPnum(int totalPnum) {  
  78.             this.totalPnum = totalPnum;  
  79.         }  
  80.   
  81.         public List<?> getBannerList() {  
  82.             return bannerList;  
  83.         }  
  84.   
  85.         public void setBannerList(List<?> bannerList) {  
  86.             this.bannerList = bannerList;  
  87.         }  
  88.   
  89.         public List<ListEntity> getList() {  
  90.             return list;  
  91.         }  
  92.   
  93.         public void setList(List<ListEntity> list) {  
  94.             this.list = list;  
  95.         }  
  96.   
  97.         public static class AdvEntity {  
  98.             
  99.             private String imgURL;  
  100.             private String dataId;  
  101.             private String htmlURL;  
  102.             private String shareURL;  
  103.             private String title;  
  104.   
  105.             public String getImgURL() {  
  106.                 return imgURL;  
  107.             }  
  108.   
  109.             public void setImgURL(String imgURL) {  
  110.                 this.imgURL = imgURL;  
  111.             }  
  112.   
  113.             public String getDataId() {  
  114.                 return dataId;  
  115.             }  
  116.   
  117.             public void setDataId(String dataId) {  
  118.                 this.dataId = dataId;  
  119.             }  
  120.   
  121.             public String getHtmlURL() {  
  122.                 return htmlURL;  
  123.             }  
  124.   
  125.             public void setHtmlURL(String htmlURL) {  
  126.                 this.htmlURL = htmlURL;  
  127.             }  
  128.   
  129.             public String getShareURL() {  
  130.                 return shareURL;  
  131.             }  
  132.   
  133.             public void setShareURL(String shareURL) {  
  134.                 this.shareURL = shareURL;  
  135.             }  
  136.   
  137.             public String getTitle() {  
  138.                 return title;  
  139.             }  
  140.   
  141.             public void setTitle(String title) {  
  142.                 this.title = title;  
  143.             }  
  144.         }  
  145.   
  146.         public static class ListEntity {  
  147.               
  148.   
  149.             private int airTime;  
  150.             private String duration;  
  151.             private String loadtype;  
  152.             private int score;  
  153.             private String angleIcon;  
  154.             private String dataId;  
  155.             private String description;  
  156.             private String loadURL;  
  157.             private String shareURL;  
  158.             private String pic;  
  159.             private String title;  
  160.             private String roomId;  
  161.   
  162.             public int getAirTime() {  
  163.                 return airTime;  
  164.             }  
  165.   
  166.             public void setAirTime(int airTime) {  
  167.                 this.airTime = airTime;  
  168.             }  
  169.   
  170.             public String getDuration() {  
  171.                 return duration;  
  172.             }  
  173.   
  174.             public void setDuration(String duration) {  
  175.                 this.duration = duration;  
  176.             }  
  177.   
  178.             public String getLoadtype() {  
  179.                 return loadtype;  
  180.             }  
  181.   
  182.             public void setLoadtype(String loadtype) {  
  183.                 this.loadtype = loadtype;  
  184.             }  
  185.   
  186.             public int getScore() {  
  187.                 return score;  
  188.             }  
  189.   
  190.             public void setScore(int score) {  
  191.                 this.score = score;  
  192.             }  
  193.   
  194.             public String getAngleIcon() {  
  195.                 return angleIcon;  
  196.             }  
  197.   
  198.             public void setAngleIcon(String angleIcon) {  
  199.                 this.angleIcon = angleIcon;  
  200.             }  
  201.   
  202.             public String getDataId() {  
  203.                 return dataId;  
  204.             }  
  205.   
  206.             public void setDataId(String dataId) {  
  207.                 this.dataId = dataId;  
  208.             }  
  209.   
  210.             public String getDescription() {  
  211.                 return description;  
  212.             }  
  213.   
  214.             public void setDescription(String description) {  
  215.                 this.description = description;  
  216.             }  
  217.   
  218.             public String getLoadURL() {  
  219.                 return loadURL;  
  220.             }  
  221.   
  222.             public void setLoadURL(String loadURL) {  
  223.                 this.loadURL = loadURL;  
  224.             }  
  225.   
  226.             public String getShareURL() {  
  227.                 return shareURL;  
  228.             }  
  229.   
  230.             public void setShareURL(String shareURL) {  
  231.                 this.shareURL = shareURL;  
  232.             }  
  233.   
  234.             public String getPic() {  
  235.                 return pic;  
  236.             }  
  237.   
  238.             public void setPic(String pic) {  
  239.                 this.pic = pic;  
  240.             }  
  241.   
  242.             public String getTitle() {  
  243.                 return title;  
  244.             }  
  245.   
  246.             public void setTitle(String title) {  
  247.                 this.title = title;  
  248.             }  
  249.   
  250.             public String getRoomId() {  
  251.                 return roomId;  
  252.             }  
  253.   
  254.             public void setRoomId(String roomId) {  
  255.                 this.roomId = roomId;  
  256.             }  
  257.         }  
  258.     }  
  259. }  



封裝工具類:

RequestApi接口
  1. public interface RequestApi {  
  2.     public static final String BASE_URL = "http://api.svipmovie.com/front/";  
  3.   
  4.     //get和RxJava  
  5.     @GET("columns/getVideoList.do?catalogId=402834815584e463015584e539330016&pnum=2")  
  6.     Observable<Bean> getData();  
  7.   
  8.     @Streaming  
  9.     @POST("{fileName}")  
  10.     Call<ResponseBody> downloadFile(@Path("fileName") String fileName, @Header("Range") String range);  
  11.   
  12.     @Streaming  
  13.     @POST("{fileName}")  
  14.     Call<ResponseBody> getFileLenght(@Path("fileName") String fileName);  
  15. }  
RetrofitUtils類:
  1. public class RetrofitUtils {  
  2.     //支持RxJava  
  3.     public static RequestApi getNetDatas(){  
  4.         OkHttpClient client = new OkHttpClient.Builder()  
  5.                 .connectTimeout(5, TimeUnit.SECONDS)  
  6.                 .readTimeout(5, TimeUnit.SECONDS)  
  7. //                .addNetworkInterceptor(new MyInterceptro())  
  8.                 .build();  
  9.   
  10.         Retrofit retrofit = new Retrofit.Builder()  
  11.                 .addCallAdapterFactory(RxJavaCallAdapterFactory.create())  
  12.                 .addConverterFactory(GsonConverterFactory.create())  
  13.                 .client(client)  
  14.                 .baseUrl(RequestApi.BASE_URL)  
  15.                 .build();  
  16.   
  17.         RequestApi api = retrofit.create(RequestApi.class);  
  18.   
  19.         return api;  
  20.     }  
  21.   
  22.   
  23.     public static RequestApi download(){  
  24.         OkHttpClient client = new OkHttpClient.Builder()  
  25.                 .connectTimeout(5, TimeUnit.SECONDS)  
  26.                 .readTimeout(5, TimeUnit.SECONDS)  
  27.                 //.addNetworkInterceptor(new MyInterceptro())  
  28.                 .build();  
  29.   
  30.         Retrofit retrofit = new Retrofit.Builder()  
  31.                 .client(client)  
  32.                 .baseUrl("http://10.0.2.2:8080/aaa/")  
  33.                 .build();  
  34.   
  35.         RequestApi api = retrofit.create(RequestApi.class);  
  36.   
  37.         return api;  
  38.     }  
  39. }  


view層:

  1. public interface IRecyView {  
  2.     void showRecy(Bean bean);  
  3. }  


model層:

IRecyModel接口
  1. public interface IRecyModel {  
  2.     void recy(Observer<Bean> observer);  
  3. }  
RecyModel是IRecyView的實現類
  1. public class RecyModel implements IRecyModel {  
  2.     @Override  
  3.     public void recy(Observer<Bean> observer) {  
  4.         //OkHttpUtils.getInstance().doGet("http://api.svipmovie.com/front/columns/getVideoList.do?catalogId=402834815584e463015584e539330016", callback);  
  5.         RetrofitUtils.getNetDatas().getData()  
  6.         .subscribeOn(Schedulers.io())   //定義被觀察者在子線程執行  
  7.         .observeOn(AndroidSchedulers.mainThread())  //定義觀察者在主線程執行  
  8.         .subscribe(observer);  
  9.     }  
  10. }  

presenter層:

  1. public class RecyPresenter {  
  2.     private IRecyView view;  
  3.     private IRecyModel model;  
  4.   
  5.   
  6.     public RecyPresenter(IRecyView view) {  
  7.         this.view = view;  
  8.         model = new RecyModel();  
  9.     }  
  10.   
  11.     public void showRecy(){  
  12.         model.recy(new Observer<Bean>() {  
  13.             @Override  
  14.             public void onCompleted() {  
  15.                 Log.i("我用retrofit+RxJava好使啦""onCompleted: ");  
  16.             }  
  17.   
  18.             @Override  
  19.             public void onError(Throwable e) {  
  20.                 Log.i("我用retrofit+RxJava好使啦""onError: ");  
  21.             }  
  22.   
  23.             @Override  
  24.             public void onNext(Bean bean) {  
  25.                 Log.i("我用retrofit+RxJava好使啦""onNext: ");  
  26.                 view.showRecy(bean);  
  27.             }  
  28.         });  
  29.     }  
  30.   
  31.     //解綁  
  32.     public void onDestory(){  
  33.         view = null;  
  34.     }  
  35. }  

適配器:

  1. public class MyRecyAdapter extends RecyclerView.Adapter<MyRecyAdapter.MyViewHolder>{  
  2.     private Context context;  
  3.     private Bean bean;  
  4.   
  5.     public MyRecyAdapter(Context context, Bean bean) {  
  6.         this.context = context;  
  7.         this.bean = bean;  
  8.     }  
  9.   
  10.     @Override  
  11.     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
  12.         View view = LayoutInflater.from(context).inflate(R.layout.recy_item, parent, false);  
  13.         MyViewHolder holder = new MyViewHolder(view);  
  14.         return holder;  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onBindViewHolder(MyViewHolder holder, int position) {  
  19.         Glide.with(context).load(bean.getRet().getList().get(position).getPic()).into(holder.iv_item);  
  20.         holder.tv_item.setText(bean.getRet().getList().get(position).getDescription());  
  21.     }  
  22.   
  23.     @Override  
  24.     public int getItemCount() {  
  25.         return bean.getRet().getList().size();  
  26.     }  
  27.   
  28.     static class MyViewHolder extends RecyclerView.ViewHolder{  
  29.   
  30.         ImageView iv_item;  
  31.         TextView tv_item;  
  32.   
  33.         public MyViewHolder(View itemView) {  
  34.             super(itemView);  
  35.             iv_item = itemView.findViewById(R.id.iv_item);  
  36.             tv_item = itemView.findViewById(R.id.tv_item);  
  37.         }  
  38.     }  
  39. }  


MainActivity:

  1. //1.權限和依賴  
  2. //2.佈局文件  
  3. //3.生成實體bean類  
  4. //4.封裝工具類 Retrofit + RxJava + OkHttp  
  5. //5.搭建MVP架構  
  6. //6.創建適配器  
  7. //7.在Activity或者Fragment中進行加載佈局管理器和綁定適配器  
  8. public class MainActivity extends AppCompatActivity implements IRecyView{  
  9.   
  10.     private XRecyclerView xrv;  
  11.     private RecyPresenter presenter;  
  12.   
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.   
  18.         initView();  
  19.         presenter = new RecyPresenter(this);  
  20.         presenter.showRecy();  
  21.     }  
  22.   
  23.   
  24.     private void initView() {  
  25.         xrv = (XRecyclerView) findViewById(R.id.xrv);  
  26.         LinearLayoutManager manager = new LinearLayoutManager(this);  
  27.         manager.setOrientation(LinearLayoutManager.VERTICAL);  
  28.         xrv.setLayoutManager(manager);  
  29.         //下面是加載更多的方法  
  30.     }  
  31.     @Override  
  32.     public void showRecy(Bean bean) {  
  33.         MyRecyAdapter myRecyAdapter = new MyRecyAdapter(this, bean);  
  34.         xrv.setAdapter(myRecyAdapter);  
  35.     }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章