Retrofit2+RxAndroid2进行简单的网络请求

最近听说Retrofit2+RxAndroid2很火,所以简单的了解了下Retrofit2+RxAndroid2。

1:添加依赖

     compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
   //compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'//retrofit现在只支持到rxjava1.XX
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'// 大神写的这个库可以支持到rxjava2.X
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

    2:创建Retroft

public class RetrofitManager {

    private static ParentApi mParentApi = null;
    private static String mIp = Constant.ip;
    private static int mHost = Constant.port;

    private RetrofitManager(){}

    private static synchronized Retrofit getRetrofit(){
        // Log信息拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别,决定了log显示的详细程度
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(httpLoggingInterceptor);
        //超时时间设置,默认60        builder.readTimeout(60000, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(60000, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(60000, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        //自动管理cookie(或者叫session的保持
        builder.cookieJar(new CookieJar() {
            private final HashMap, List> cookieStore = new HashMap<>();

            @Override
            public void saveFromResponse(HttpUrl url, List cookies) {
                cookieStore.put(url, cookies);
            }

            @Override
            public List loadForRequest(HttpUrl url) {
                List cookies = cookieStore.get(url);
                return cookies != null ? cookies : new ArrayList();
            }
        });

        OkHttpClient client = builder.build();

        return new Retrofit.Builder()
                .client(client)
                .baseUrl(String.format(Api.baseUrl, Constant.ip, Constant.port))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static synchronized ParentApi getApi(){
        if(null == mParentApi){
            mParentApi = getRetrofit().create(ParentApi.class);
            return mParentApi;
	//这里是根据自己的逻辑写的,我用到的是IP跟port会动态改变的
        } else if(!mIp.equals(Constant.ip) || mHost != Constant.port){
            mIp = Constant.ip;
            mHost = Constant.port;
            mParentApi = getRetrofit().create(ParentApi.class);
            return mParentApi;
        }
        return mParentApi;
    }

}

3:创建注解

public interface ParentApi {

    /*************************************************SSN**************************************************************/

    @POST("your interface")
    Observable getAllRecorderStates(@Body Map,String> map);

}

4:RxAndroid使用

Map,String> map = new HashMap<>();
map.put("key", "value");
map.put("key2", "value2");
setLoadingState(LOAD_STATE.STATE_LOADING);
Observable observable = RetrofitManager.getApi().getAllRecorderStates(map);
observable.subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer() {
            @Override
            public void onSubscribe(Disposable d) {
                //取消订阅
            }

            @Override
            public void onNext(SchoolBean schoolBean) {
                //可实现自己的逻辑
            }

            @Override
            public void onError(Throwable e) {
                setLoadingState(LOAD_STATE.STATE_EMPTY);
            }

            @Override
            public void onComplete() {

            }
        });

你可能感兴趣的:(移动开发,个人文章,android,retrofit2,rxandroid2,网络请求)