近幾年,Retrofit猶如燎原之火搬席捲了整個Android界。要是不懂Retrofit,簡直很差意思出門。。。
因爲近幾個項目都沒用到Retrofit,無奈只能業餘時間本身擼一下,寫的很差的地方,還請不吝賜教。
要集成retrofit,在app的build.gradle中添加庫以來就能夠:java
compile 'com.squareup.retrofit2:retrofit:2.3.0'
若是須要集成json解析,還須要添加庫:react
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
若是還須要集成rxjava,還須要添加庫:android
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
添加庫完畢,接下來須要定義請求接口:json
public interface TestService { /** * 獲取新聞 使用rxjava * @return */ @POST(AppConstance.NEWS_URL) Observable<NewsBean> getNewsWithRxJava(@Query("key") String key, @Query("type") String type); /** * 獲取新聞 不使用rxjava * @return */ @POST(AppConstance.NEWS_URL) Call<ResponseBody> getNewsWithoutRxJava(@Query("key") String key, @Query("type") String type); }
這個接口是我在聚合數據申請的測試接口,我將其分爲兩種狀況:使用rajava、不使用rxjava。
正常使用中,都會將Retrofit進行封裝,我在這裏將其簡單的封裝:app
public class RetrofitUtil { private volatile static RetrofitUtil sInstance; private Retrofit mRetrofit; private TestService mTestService; private RetrofitUtil(){ mRetrofit = new Retrofit.Builder() .baseUrl(AppConstance.APP_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); mTestService = mRetrofit.create(TestService.class); } public static RetrofitUtil getInstance(){ if (sInstance == null){ synchronized(RetrofitUtil.class){ if (sInstance == null){ sInstance = new RetrofitUtil(); } } } return sInstance; } public TestService getTestService(){ return mTestService; } }
萬事具有,如今開始在Activity中測試Retrofit。
xml文件:ide
<?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" tools:context="org.shenchanghui.retrofit2withrxjava2_demo.MainActivity"> <Button android:id="@+id/btn_get_news_with_rx_java" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:text="獲取新聞(使用rxjava)" /> <Button android:id="@+id/btn_get_news_without_rx_java" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentStart="true" android:layout_below="@+id/btn_get_news_with_rx_java" android:text="獲取新聞(不使用Rxjava)" /> </RelativeLayout>
界面截圖以下:
測試
在Activity中請求數據,首先,不使用rajava:gradle
findViewById(R.id.btn_get_news_without_rx_java).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { long time1 = System.currentTimeMillis(); Call<ResponseBody> call = RetrofitUtil.getInstance().getTestService() .getNewsWithoutRxJava("8bf17cf1c321723f060d5dc5c4da871a", "top"); long time2 = System.currentTimeMillis(); Log.e("MainActivity", "請求耗時:" + (time2 - time1) + "ms"); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { String result = response.body().string(); Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); Log.e("MainActivity", "Thread.currentThread():" + Thread.currentThread()); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show(); } }); } });
運行項目,成功獲取返回的json字符串。
log截圖:
ui
建立實體類,用GsonFormat插件將獲取的json字符串生成實體類,用以解析json。
實體類:this
public class NewsBean { private String reason; private ResultBean result; private int error_code; @Override public String toString() { return "NewsBean{" + "reason='" + reason + '\'' + ", result=" + result + ", error_code=" + 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; } public static class ResultBean { private String stat; private List<DataBean> data; @Override public String toString() { return "ResultBean{" + "stat='" + stat + '\'' + ", data=" + 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; @Override public String toString() { return "DataBean{" + "uniquekey='" + uniquekey + '\'' + ", title='" + title + '\'' + ", date='" + date + '\'' + ", category='" + category + '\'' + ", author_name='" + author_name + '\'' + ", url='" + url + '\'' + ", thumbnail_pic_s='" + thumbnail_pic_s + '\'' + ", thumbnail_pic_s02='" + thumbnail_pic_s02 + '\'' + ", thumbnail_pic_s03='" + 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; } } } }
接下里,使用rxjava,請求數據(自動返回解析好的數據):
findViewById(R.id.btn_get_news_with_rx_java).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { RetrofitUtil.getInstance().getTestService() .getNewsWithRxJava("8bf17cf1c321723f060d5dc5c4da871a", "top") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<NewsBean>() { private Disposable mDisposable; @Override public void onSubscribe(Disposable d) { mDisposable = d; } @Override public void onNext(NewsBean value) { Toast.makeText(MainActivity.this, value.toString(), Toast.LENGTH_SHORT).show(); mDisposable.dispose();//註銷 } @Override public void onError(Throwable e) { Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); mDisposable.dispose();//註銷 } @Override public void onComplete() { } }); } });
運行程序,成功獲取請求結果。
效果截圖:
小小Demo,供你們參考,請你們不吝賜教!