Android封裝Retrofit2+OkHttp3+RxJava網(wǎng)絡(luò)請求

現(xiàn)在Android 市面上很火的當(dāng)然是 Retrofit+RxJava + OkHttp, 功能強(qiáng)大,簡單易用,因此選用這套方案來改造網(wǎng)絡(luò)庫。

簡介:

Retrofit: Retrofit是Square 公司開發(fā)的一款正對Android 網(wǎng)絡(luò)請求的框架。底層基于OkHttp 實(shí)現(xiàn),OkHttp 已經(jīng)得到了google 官方的認(rèn)可。Retrofit官網(wǎng)

OkHttp: 也是Square 開源的網(wǎng)絡(luò)請求庫

RxJava:RxJava 在 GitHub 主頁上的自我介紹是 "a library for composing asynchronous and event-based programs using observable sequences for the Java VM"(一個(gè)在 Java VM 上使用可觀測的序列來組成異步的、基于事件的程序的庫)。這就是 RxJava ,概括得非常精準(zhǔn)??傊褪亲尞惒讲僮髯兊梅浅:唵?。

各自的職責(zé):Retrofit 負(fù)責(zé)請求的數(shù)據(jù)和請求的結(jié)果,使用接口的方式呈現(xiàn),OkHttp 負(fù)責(zé)請求的過程,RxJava 負(fù)責(zé)異步,各種線程之間的切換。

RxJava + Retrofit + okHttp 已成為當(dāng)前Android 網(wǎng)絡(luò)請求最流行的方式。

一、添加依賴庫

    //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'

二、生成接口實(shí)例的管理類

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)//連接超時(shí)時(shí)間
                .writeTimeout(DEFAULT_WRITE_TIME, TimeUnit.SECONDS)//設(shè)置寫操作超時(shí)時(shí)間
                .readTimeout(DEFAULT_READ_TIME, TimeUnit.SECONDS)//設(shè)置讀操作超時(shí)時(shí)間
                .build();

        retrofit = new Retrofit.Builder()
                .client(okHttpClient)//設(shè)置使用okhttp網(wǎng)絡(luò)請求
                .baseUrl(REQUEST_PATH)//設(shè)置服務(wù)器路徑
                .addConverterFactory(GsonConverterFactory.create())//添加轉(zhuǎn)化庫,默認(rèn)是Gson
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加回調(diào)庫,采用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設(shè)計(jì)模式(生產(chǎn)者模式),將一個(gè)復(fù)雜的構(gòu)建與其表示相分離。
同樣升級到okhttp3后,也使用build設(shè)計(jì)模式。

okhttp參數(shù)說明:
    cookieJar(new CookiesManager()): 設(shè)置一個(gè)自動(dòng)管理cookies的管理器
    addInterceptor(new MyIntercepter()):添加攔截器
    addNetworkInterceptor(new
    CookiesInterceptor(MyApplication.getInstance().getApplicationContext())):添加網(wǎng)絡(luò)連接器
    connectTimeout(30, TimeUnit.SECONDS):請求超時(shí)時(shí)間 
    writeTimeout(30,TimeUnit.SECONDS):寫入超時(shí)時(shí)間 
    readTimeout(30, TimeUnit.SECONDS):讀取超時(shí)時(shí)間

三、創(chuàng)建接口類

public interface MovieService {
        //獲取豆瓣前20的榜單
        @GET("top250")
        Observable<movieTopReq> getMovicTop(@Query("start") int start, @Query("count") int count);
    }

接口已經(jīng)創(chuàng)建出來了,Retrofit是用注解來完成設(shè)置的,要訪問的url,請求方式,請求頭。
常用的注解:
@GET GET請求方式
@POST POST請求方式
@Query GET請求參數(shù)
@Header用來添加Header請求頭
@FormUrlEncoded post請求頭標(biāo)示
其他注解請求方式:
@PUT 表示這是一個(gè)PUT請求
@DELETE 表示這是一個(gè)DELETE請求
@HEAD 表示這是一個(gè)HEAD請求
@OPTIONS 表示這是一個(gè)OPTION請求
@PATCH 表示這是一個(gè)PAT請求

四、創(chuàng)建實(shí)現(xiàn)接口來方便調(diào)用

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())//子線程訪問網(wǎng)絡(luò)
                .observeOn(AndroidSchedulers.mainThread())//回調(diào)到主線程
                .subscribe(observer);
    }
}

把網(wǎng)絡(luò)接口統(tǒng)一放到一個(gè)接口類中,讓Retrofit創(chuàng)建實(shí)現(xiàn)接口來方便調(diào)用。setSubscribe方法其實(shí)就是插入觀察者。

五、activity調(diào)用

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() {
        //調(diào)用封裝好的retrofit請求方法
        HttpEngine.getDuoBanTop(0, 20, new Observer<movieTopReq>() {
            @Override
            public void onCompleted() {
                //完成
            }

            @Override
            public void onError(Throwable e) {
                //失敗
                Log.i("retrofit==111=", "請求錯(cuò)誤:"+e.getMessage());
            }

            @Override
            public void onNext(movieTopReq movieTopReq) {
                //成功
                Log.i("retrofit==222=", movieTopReq.getTitle()+"---"+movieTopReq.getCount()
                        +"---"+movieTopReq.getStart()+"---"+movieTopReq.getTotal()+"---"+movieTopReq.getSubjects());
            }
        });
    }
}

需要Demo的童鞋公眾號回復(fù):"Retrofit"即可獲取


以下是個(gè)人公眾號(longxuanzhigu),之后發(fā)布的文章會(huì)同步到該公眾號,方便交流學(xué)習(xí)Android知識及分享個(gè)人愛好文章:


這里寫圖片描述
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容