1. 程式人生 > >ReTroFit+RxJava + HttpUtils

ReTroFit+RxJava + HttpUtils

////API
public interface Api {
    @FormUrlEncoded
    @POST("user/login")
    //Observable<UserInfo> login(@Field("mobile") String mobile, @Field("password") String password);
    Observable<UserInfo> login(@Field("mobile") String mobile, @Field("password") String password);
}

///Constant
public class Constant {
    public static final String BASE_URL = "https://www.zhaoapi.cn";

}

//HttpUtils
public class HttpUtils {

    public final Api apiclient;

    private HttpUtils() {
        //例項化
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                //新增攔截器
                .addNetworkInterceptor(new LoggingInterceptor())
                .build();

        Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();

        apiclient = retrofit.create(Api.class);


    }

     class LoggingInterceptor implements Interceptor {
         @Override
         public Response intercept(Chain chain) throws IOException {
             Request request = chain.request();

             long t1 = System.nanoTime();


             Response proceed = chain.proceed(request);

             long t2 = System.nanoTime();
             return proceed;
         }
     }

     private static  class  GetHttpUtilsInstance{

        private static  HttpUtils  httpUtils=new HttpUtils();


     }

     public  static  HttpUtils getHttpUtilsInstance(){
        return   GetHttpUtilsInstance.httpUtils;

     }

}


//MianActivity
    private void text3() {
        io.reactivex.Observable<UserInfo> login = HttpUtils.getHttpUtilsInstance().apiclient.login("18611520300", "123123");

        login.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UserInfo userInfo) {
                        Log.e("qing", "jjj" + userInfo.getData().getCreatetime());


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}

依賴

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.0.2'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'