首先在學習他們的結合使用前,我們需要簡單的學習它們:
Rxjava2的簡單使用與基本操作符
Retrofit2網絡框架的使用
這里我使用了Bmob作為簡單的后臺管理,通過登錄案列以便查看
一 配置
//rxjava2
compile 'io.reactivex.rxjava2:rxjava:2.1.10'
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
//retrofit2
compile 'com.squareup.retrofit2:retrofit:2.3.0'
//Retrofit到Gson進行轉換的庫
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//Retrofit到RxJava進行轉換的庫
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//如果需要添加HttpLoggingInterceptor進行調試,添加如下依賴
compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'
compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'
二 使用
2.1 創建接口
interface HttpInterface {
//登錄
@GET("1/login")
Observable<User> login(@QueryMap Map<String, String> data);
}
2.2 創建Retrofit2工具類
public class RetrofitHttp {
public static HttpInterface getHttpInterface() {
//保存cookie信息
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
// Retrofit是基于OkHttpClient的,可以創建一個OkHttpClient進行一些配置
OkHttpClient httpClient = new OkHttpClient.Builder()
// 添加通用的Header
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request build = request.newBuilder()
//添加headler
.addHeader("X-Bmob-Application-Id", "88d31c7422f7bb24b4b162743c436fdc")
.addHeader("X-Bmob-REST-API-Key", "d06ffe71668b518ffec6839436d5ed16")
.method(request.method(), request.body())
.build();
return chain.proceed(build);
}
})
//添加HttpLoggingInterceptor攔截器方便調試接口
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
}
}).setLevel(HttpLoggingInterceptor.Level.BASIC))
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.cookieJar(new JavaNetCookieJar(cookieManager))
.retryOnConnectionFailure(true)
.build();
return new Retrofit.Builder()
.baseUrl("https://api.bmob.cn/")
// 添加Gson轉換器
.addConverterFactory(GsonConverterFactory.create())
// 添加Retrofit到RxJava的轉換器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient)
.build()
.create(HttpInterface.class);
}
}
2.3 封裝方便調用
public class ApiServer {
/**
* 用戶登錄
*/
public static void loginModel(Map<String, String> data, Observer<User> observer) {
RetrofitHttp.getHttpInterface()
.login(data)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
}
2. 4 調用方法,訪問網絡
Map<String,String>map=new ArrayMap<>();
map.put("username","admin");
map.put("password","admin");
ApiServer.loginModel(map, new Observer<User>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull User user) {
Log.i(TAG, "onNext: "+user);
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});