Retrofit+OkHttp+RxJava的正确使用方式

引入包

//retrofit
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okio:okio:1.5.0'
    //rxjava
    compile 'io.reactivex:rxjava:1.2.0'
    compile 'io.reactivex:rxandroid:1.2.1'

定义订阅者

/**
 * Created by 87901 on 2016/5/5.
 * RxJava中的订阅者
 */
public class BaseSubscriber extends Subscriber {
    private Context context;
    public BaseSubscriber(Context context){
        this.context=context;
    }
    @Override
    public void onStart() {
    }
    @Override
    public void onNext(T t) {
        Toast.makeText(context, ((BaseBean) t).msg,Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onCompleted() {
    }
    @Override
    public void onError(Throwable throwable) {
        try {
            Toast.makeText(context, "网络错误",Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

定义Http请求类

public class HttpHelp {

    private static Retrofit instance;
    private HttpHelp(){}
    /**
     * 不需要在请求头添加东西,可以做成单例模式
     * @return
     */
    public static Retrofit getInstance(){
        if (instance==null){
            synchronized (HttpHelp.class){
                if (instance==null){
                    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    OkHttpClient client = new OkHttpClient.Builder()
                            .addInterceptor(interceptor)
                            .retryOnConnectionFailure(true)
                            .connectTimeout(5, TimeUnit.SECONDS)
                            .readTimeout(600,TimeUnit.SECONDS)
                            .writeTimeout(600,TimeUnit.SECONDS)
                            .build();

                    Gson gson = new GsonBuilder()
                            .setLenient()
                            .create();
                    instance = new Retrofit.Builder()
                            .baseUrl(Constants.HOST)
                            .client(client)
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create(gson))
                            .build();
                }
            }
        }
        return instance;
    }
}

定义接口

public interface RemoteApi {
    //获取热门城市
    @GET("search/hots")
    Observable> getHotSearchData();
    //登录
    @POST("/api/user/login")
    @FormUrlEncoded
    Observable> login(@Field("username") String username, @Field("password") String password);
    ...
}

调用

HttpHelp.getInstance().create(RemoteApi.class).login(etPhoneNumber.getText().toString().trim()
                            ,etPassword.getText().toString().trim())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseSubscriber>(LoginActivity.this) {
                                @Override
                                public void onNext(BaseBean baseBean) {
                                    super.onNext(baseBean);
                                    //处理请求成功后的业务逻辑
                                }
                               @Override
                                public void onError(Throwable throwable) {
                                    super.onError(throwable);
                                   //请求异常
                                }
                            });

你可能感兴趣的:(Retrofit+OkHttp+RxJava的正确使用方式)