Retrofit+Rxjava1.0請求資料
阿新 • • 發佈:2019-01-09
這是一篇淺顯的Rxjava+Retrofit文章,從初學者出發,感覺如果工作中沒有充足發揮自學技能的專案,直接去看大佬們寫的很深入的講解,特別容易遺忘、懵甚至不理解,所以我決定寫一篇淺顯的使用Rxjava+Retrofit的文章。
我訪問的是“聚合資料”提供的新聞頭條連結(“http://v.juhe.cn/toutiao/index?type=top&key=28aa4ac2a689c881a4e6e51cf918d695”)
1.新增依賴庫
/*retrofit2*/ implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4' implementation 'com.squareup.retrofit2:retrofit:2.0.2' implementation 'com.squareup.retrofit2:converter-gson:2.0.2' implementation 'com.squareup.okhttp3:okhttp:3.3.0' implementation 'com.squareup.okio:okio:1.7.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.2.0' implementation 'io.reactivex:rxandroid:1.1.0' implementation 'io.reactivex:rxjava:1.1.0' implementation'com.squareup.retrofit2:retrofit:2.1.0' implementation'com.squareup.retrofit2:adapter-rxjava:2.1.0' /*retrofit2*/
2.建立bean(此為請求資料為json的實體類)
import java.util.List; /** * 作者:Android * 時間:2018/9/12 15:55 * 功能: */ public class RetrofitRxjavaResult { private String reason;//成功的返回 private ResultBean result; private int error_code; public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public int getError_code() { return error_code; } public void setError_code(int error_code) { this.error_code = error_code; } @Override public String toString() { return "RetrofitRxjavaResult{" + "reason='" + reason + '\'' + ", result=" + result + ", error_code=" + error_code + '}'; } public static class ResultBean { private String stat; private List<DataBean> data; public String getStat() { return stat; } public void setStat(String stat) { this.stat = stat; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { private String uniquekey; private String title; private String date; private String category; private String author_name; private String url; private String thumbnail_pic_s; private String thumbnail_pic_s02; private String thumbnail_pic_s03; public String getUniquekey() { return uniquekey; } public void setUniquekey(String uniquekey) { this.uniquekey = uniquekey; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getAuthor_name() { return author_name; } public void setAuthor_name(String author_name) { this.author_name = author_name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getThumbnail_pic_s() { return thumbnail_pic_s; } public void setThumbnail_pic_s(String thumbnail_pic_s) { this.thumbnail_pic_s = thumbnail_pic_s; } public String getThumbnail_pic_s02() { return thumbnail_pic_s02; } public void setThumbnail_pic_s02(String thumbnail_pic_s02) { this.thumbnail_pic_s02 = thumbnail_pic_s02; } public String getThumbnail_pic_s03() { return thumbnail_pic_s03; } public void setThumbnail_pic_s03(String thumbnail_pic_s03) { this.thumbnail_pic_s03 = thumbnail_pic_s03; } } } }
3.Retrofit與Rxjava結合的類
package com.example.androidvideo.activity; import android.app.Activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import com.example.androidvideo.R; import com.example.androidvideo.adpater.MyListViewAdapter; import com.example.androidvideo.bean.RetrofitRxjavaResult; import com.example.androidvideo.interfaces.NewsService; import com.example.androidvideo.utils.LogUtils; import com.example.androidvideo.utils.ToastUtils; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Observer; import rx.Scheduler; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * 作者:Android * 時間:2018/9/12 15:51 * 功能:Retrofit和Rxjava的網路請求 */ public class RetrofitRxjavaActivity extends Activity { private static final String TAG = RetrofitRxjavaActivity.class.getSimpleName(); private static final long TIMEOUT = 5000; private static final String BASE_URL = "http://v.juhe.cn/toutiao/"; private ListView listView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_retrorxjava); initView(); requestServer(); } private void initView() { listView = (ListView) findViewById(R.id.listView); } /** * 請求網路 */ private void requestServer() { /*OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {//新增網路訪問Header @Override public Response intercept(Chain chain) throws IOException { Request.Builder builder = chain.request().newBuilder(); builder.addHeader("token", "123"); return chain.proceed(builder.build()); } }) .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { //獲取網路錯誤資訊 Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } }).setLevel(HttpLoggingInterceptor.Level.BASIC)) .connectTimeout(TIMEOUT, TimeUnit.SECONDS)//連結超時 .readTimeout(TIMEOUT, TimeUnit.SECONDS)//讀取超時 .build();*/ OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.SECONDS) .readTimeout(5000, TimeUnit.SECONDS) .build(); Gson buildGson = new GsonBuilder() .serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) .create(); NewsService newsService = new Retrofit.Builder().baseUrl(BASE_URL) .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//新增Rxjava支援 .addConverterFactory(GsonConverterFactory.create(buildGson)) .client(okHttpClient) .build().create(NewsService.class); Observable<RetrofitRxjavaResult> observable = newsService.getNews("top", "28aa4ac2a689c881a4e6e51cf918d695"); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<RetrofitRxjavaResult>() { @Override public void onCompleted() { Log.d(TAG, "onCompleted() called"); } @Override public void onError(Throwable e) { Log.d(TAG, "onError() called"); } @Override public void onNext(RetrofitRxjavaResult retrofitRxjavaResult) { Log.d(TAG, "onNext:" + retrofitRxjavaResult); if (retrofitRxjavaResult != null) { RetrofitRxjavaResult.ResultBean result = retrofitRxjavaResult.getResult(); if (result != null) { List<RetrofitRxjavaResult.ResultBean.DataBean> data = result.getData(); MyListViewAdapter adapter = new MyListViewAdapter(RetrofitRxjavaActivity.this, data); listView.setAdapter(adapter); } } else { ToastUtils.showText("伺服器資料錯誤"); } } }); } }
4.ListView的BaseAdapter
package com.example.androidvideo.adpater; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.androidvideo.R; import com.example.androidvideo.bean.RetrofitRxjavaResult; import com.example.androidvideo.customView.MyImageView; import java.util.List; /** * 作者:Android * 時間:2018/9/12 17:11 * 功能:ListView的介面卡 */ public class MyListViewAdapter extends BaseAdapter { private final List<RetrofitRxjavaResult.ResultBean.DataBean> data; private LayoutInflater mInflater; public MyListViewAdapter(Context context, List<RetrofitRxjavaResult.ResultBean.DataBean> data) { mInflater = LayoutInflater.from(context); this.data = data; } @Override public int getCount() { return data.size(); } @Override public Object getItem(int i) { return data.get(i); } @Override public long getItemId(int i) { return 0; } @Override public View getView(int postion, View convertView, ViewGroup viewGroup) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item, null, false); //載入佈局 holder = new ViewHolder(); holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title); holder.tvDate = (TextView) convertView.findViewById(R.id.tv_date); holder.imageView = (MyImageView) convertView.findViewById(R.id.image_view); convertView.setTag(holder); } else { //else裡面說明,convertView已經被複用了,說明convertView中已經設定過tag了,即holder holder = (ViewHolder) convertView.getTag(); } RetrofitRxjavaResult.ResultBean.DataBean bean = data.get(postion); holder.tvTitle.setText(bean.getTitle()); holder.tvDate.setText(bean.getDate()); holder.imageView.setImageURL(bean.getThumbnail_pic_s()); return convertView; } private class ViewHolder { MyImageView imageView; TextView tvTitle; TextView tvDate; } }
整理,作為筆記。