如今Android 市面上很火的固然是 Retrofit+RxJava + OkHttp, 功能強大,簡單易用,所以選用這套方案來改造網絡庫。java
簡介:react
Retrofit: Retrofit是Square 公司開發的一款正對Android 網絡請求的框架。底層基於OkHttp 實現,OkHttp 已經獲得了google 官方的承認。Retrofit官網android
OkHttp: 也是Square 開源的網絡請求庫設計模式
RxJava:RxJava 在 GitHub 主頁上的自我介紹是 "a library for composing asynchronous and event-based programs using observable sequences for the Java VM"(一個在 Java VM 上使用可觀測的序列來組成異步的、基於事件的程序的庫)。這就是 RxJava ,歸納得很是精準。總之就是讓異步操做變得很是簡單。api
各自的職責:Retrofit 負責請求的數據和請求的結果,使用接口的方式呈現,OkHttp 負責請求的過程,RxJava 負責異步,各類線程之間的切換。服務器
RxJava + Retrofit + okHttp 已成爲當前Android 網絡請求最流行的方式。cookie
1、添加依賴庫網絡
//RxJava compile 'io.reactivex:rxjava:1.1.3' //RxAndroid compile 'io.reactivex:rxandroid:1.1.0' //retrofit compile 'com.squareup.retrofit2:retrofit:2.0.0' //retrofit依賴Gson compile 'com.squareup.retrofit2:converter-gson:2.0.0' //OkHttp compile 'com.squareup.okhttp3:okhttp:3.2.0' //retrofit依賴RxJava compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
2、生成接口實例的管理類框架
public class RetrofitServiceManager { private static final int DEFAULT_CONNECT_TIME = 10; private static final int DEFAULT_WRITE_TIME = 30; private static final int DEFAULT_READ_TIME = 30; private final OkHttpClient okHttpClient; private static final String REQUEST_PATH = "https://api.douban.com/v2/movie/"; private final Retrofit retrofit; private RetrofitServiceManager() { okHttpClient = new OkHttpClient.Builder() .connectTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)//鏈接超時時間 .writeTimeout(DEFAULT_WRITE_TIME, TimeUnit.SECONDS)//設置寫操做超時時間 .readTimeout(DEFAULT_READ_TIME, TimeUnit.SECONDS)//設置讀操做超時時間 .build(); retrofit = new Retrofit.Builder() .client(okHttpClient)//設置使用okhttp網絡請求 .baseUrl(REQUEST_PATH)//設置服務器路徑 .addConverterFactory(GsonConverterFactory.create())//添加轉化庫,默認是Gson .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加回調庫,採用RxJava .build(); } private static class SingletonHolder { private static final RetrofitServiceManager INSTANCE = new RetrofitServiceManager(); } /* * 獲取RetrofitServiceManager **/ public static RetrofitServiceManager getInstance() { return SingletonHolder.INSTANCE; } public <T> T create(Class<T> service) { return retrofit.create(service); } }
從Retrofit升級到2.0以後,就使用了build設計模式(生產者模式),將一個複雜的構建與其表示相分離。
一樣升級到okhttp3後,也使用build設計模式。異步
okhttp參數說明: cookieJar(new CookiesManager()): 設置一個自動管理cookies的管理器 addInterceptor(new MyIntercepter()):添加攔截器 addNetworkInterceptor(new CookiesInterceptor(MyApplication.getInstance().getApplicationContext())):添加網絡鏈接器 connectTimeout(30, TimeUnit.SECONDS):請求超時時間 writeTimeout(30,TimeUnit.SECONDS):寫入超時時間 readTimeout(30, TimeUnit.SECONDS):讀取超時時間
3、建立接口類
public interface MovieService { //獲取豆瓣前20的榜單 @GET("top250") Observable<movieTopReq> getMovicTop(@Query("start") int start, @Query("count") int count); }
接口已經建立出來了,Retrofit是用註解來完成設置的,要訪問的url,請求方式,請求頭。
經常使用的註解:
@GET GET請求方式
@POST POST請求方式
@Query GET請求參數
@Header用來添加Header請求頭
@FormUrlEncoded post請求頭標示
其餘註解請求方式:
@PUT 表示這是一個PUT請求
@DELETE 表示這是一個DELETE請求
@HEAD 表示這是一個HEAD請求
@OPTIONS 表示這是一個OPTION請求
@PATCH 表示這是一個PAT請求
4、建立實現接口來方便調用
public class HttpEngine { private static MovieService movieService = RetrofitServiceManager.getInstance().create(MovieService.class); /* * 獲取豆瓣電影榜單 * **/ public static void getDuoBanTop(int start, int count, Observer<movieTopReq> observer) { setSubscribe(movieService.getMovicTop(start, count), observer); } private static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) { observable.subscribeOn(Schedulers.io()) .subscribeOn(Schedulers.newThread())//子線程訪問網絡 .observeOn(AndroidSchedulers.mainThread())//回調到主線程 .subscribe(observer); } }
把網絡接口統一放到一個接口類中,讓Retrofit建立實現接口來方便調用。setSubscribe方法其實就是插入觀察者。
5、activity調用
public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); } private void initData() { //調用封裝好的retrofit請求方法 HttpEngine.getDuoBanTop(0, 20, new Observer<movieTopReq>() { @Override public void onCompleted() { //完成 } @Override public void onError(Throwable e) { //失敗 Log.i("retrofit==111=", "請求錯誤:"+e.getMessage()); } @Override public void onNext(movieTopReq movieTopReq) { //成功 Log.i("retrofit==222=", movieTopReq.getTitle()+"---"+movieTopReq.getCount() +"---"+movieTopReq.getStart()+"---"+movieTopReq.getTotal()+"---"+movieTopReq.getSubjects()); } }); } }
須要Demo的童鞋公衆號回覆:"Retrofit"便可獲取
如下是我的公衆號(longxuanzhigu),以後發佈的文章會同步到該公衆號,方便交流學習Android知識及分享我的愛好文章: