Retrofit2和RxJava2搭建Android網(wǎng)絡框架

轉(zhuǎn)自:http://ranseti.top/article/retrofit2addrxjava2
項目需要compile的資源有

compile 'com.squareup.retrofit2:retrofit:2.3.0'

Retrofit2https://github.com/square/retrofit

compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

retrofit2的Rxjava2適配器https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2

compile 'com.squareup.retrofit2:converter-gson:2.3.0'

Retrofit2的數(shù)據(jù)轉(zhuǎn)換器https://github.com/square/retrofit/tree/master/retrofit-converters/gson

以上三個需要保持版本一致,除此還需要

compile 'com.google.code.gson:gson:2.8.2'

google的Gsonhttps://github.com/google/gson

compile "io.reactivex.rxjava2:rxjava:2.1.8"

Rxjavahttps://github.com/ReactiveX/RxJava

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

RxAndroidhttps://github.com/ReactiveX/RxAndroid

compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'

okHttp的log攔截器,方便調(diào)試https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor



下面直接看代碼

  1. okHttp的配置
public class OkHttpConfigure {

    private static final long TIMEOUT = 30;

    public static OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.i("okHttp", message);
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY))
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .build();
}

2.Retrofit配置(我的Demo中用了三個Host主機,所以配置了三個)

public class RetrofitConfigure {

    /**
     * GitHub配置
     */
    private static final String GitHub_Host = "https://api.github.com";

    public static Retrofit githubRetrofit = new Retrofit.Builder()
            .baseUrl(GitHub_Host)
            .client(OkHttpConfigure.httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();


    /**
     * 物流100配置
     */
    private static final String WuLiu_Host = "http://www.kuaidi100.com";

    public static Retrofit wuLiuRetrofit = new Retrofit.Builder()
            .baseUrl(WuLiu_Host)
            .client(OkHttpConfigure.httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();


    /**
     * 圖片下載
     */
    private static String picture_Host = "https://timgsa.baidu.com";

    public static void setPicture_Host(String picture_Host) {
        RetrofitConfigure.picture_Host = picture_Host;
    }

    public static Retrofit pictureRetrofit = new Retrofit.Builder()
            .baseUrl(picture_Host)
            .client(OkHttpConfigure.httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
}

3.GitHub的Api


public interface GitHubAPI {

    //https://api.github.com/repos/square/retrofit/contributors
    @GET("/repos/{owner}/{repo}/contributors")
    Observable<List<Contributor>> getContributors(@Path("owner") String owner,
                                                  @Path("repo") String repo);

    @GET("/timg?image&quality=80&size=b9999_10000&sec=1517483557140&di=8ef2706c558749c2c9ae999e4401651d&imgtype=0&src=http%3A%2F%2Fimg5.niutuku.com%2Fphone%2F1301%2F5651%2F5651-niutuku.com-446980.jpg")
    Observable<ResponseBody> getcontributorsAvator();

    // !!! 當心大文件,當是大文件時
    @Streaming
    @GET
    Observable<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);

}

4.創(chuàng)建API的實例,定制Observer實現(xiàn)數(shù)據(jù)的異步獲取

public class ConnectHttp<T> {

    //創(chuàng)建 GitHub API 接口的一個實例。
    public static GitHubAPI getGitHubAPI() {
        return RetrofitConfigure.githubRetrofit.create(GitHubAPI.class);
    }

    //創(chuàng)建  WuLiu API 口的一個實例。
    public static WuLiuAPI getWuLiuAPI() {
        return RetrofitConfigure.wuLiuRetrofit.create(WuLiuAPI.class);
    }

    //創(chuàng)建  WuLiu API 口的一個實例。
    public static GitHubAPI getPictureAPI() {
        return RetrofitConfigure.pictureRetrofit.create(GitHubAPI.class);
    }

    /**
     * 連接網(wǎng)絡
     * @param observable
     * @param baseObserver
     */
    public static <T> void connect(Observable<T> observable, BaseObserver<T> baseObserver) {
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((baseObserver));
    }
}

5.抽取觀察者,對一些異常進行異常處理

public abstract class BaseObserver<T> implements Observer<T> {

    private Context context;

    public <T> BaseObserver(Context context) {
        this.context = context;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull T t) {
        Log.i("observer",new Gson().toJson(t));
        onResponse(t);
    }

    public abstract void onResponse(T t);

    @Override
    public void onError(@NonNull Throwable e) {
        Log.e("Observer",new Gson().toJson(e));
        if (!NetWorkUtils.isNetworkConnected(context)) {
//            NetWorkSetDialog.showSetNetworkUI(context);
            Toast.makeText(context, "沒有可用的網(wǎng)絡", Toast.LENGTH_LONG).show();
        }
        if (e.getMessage().contains("404")) {
            Toast.makeText(context, "網(wǎng)絡404錯誤", Toast.LENGTH_LONG).show();
        }
        if (e.getMessage().contains("500")) {
            Toast.makeText(context, "網(wǎng)絡500錯誤", Toast.LENGTH_LONG).show();
        }
        if(e instanceof IllegalStateException){
            Toast.makeText(context, "數(shù)據(jù)解析異常", Toast.LENGTH_LONG).show();
        }
        if(e instanceof SocketTimeoutException){
            Toast.makeText(context, "請求超時", Toast.LENGTH_LONG).show();
        }
        e.printStackTrace();
    }

    @Override
    public void onComplete() {
        Log.i("observable", "-----------已完成----------");
    }
}

6.對API進行一次包裝方便調(diào)用

public class GitHubAPIPackage {

    /**
     * 獲取GitHub倉庫貢獻者
     *
     * @param owner
     * @param repo
     * @return
     */
    public static Observable<List<Contributor>> getContributors(String owner, String repo) {
        return ConnectHttp.getGitHubAPI().getContributors(owner, repo);
    }


    /**
     * 下載頭像
     * @return
     */
    public static Observable<ResponseBody> getcontributorsAvator() {
        return ConnectHttp.getPictureAPI().getcontributorsAvator();
    }
}

7.進行調(diào)用

/**
 * 查詢retrofit貢獻者
 */
private void initData() {

        ConnectHttp.connect(GitHubAPIPackage.getContributors("square", "retrofit"),
                new BaseObserver<List<Contributor>>(context) {
                    @Override
                    public void onResponse(List<Contributor> contributors) {
                        //TODO 做你想做的
                    }
                });
}

詳細Demo參考https://github.com/heyl1989/Retrfit2AddRxJava2

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

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