最近不是很忙,用Rxjava2+Retrofit2+Okhttp3写了个网络请求的demo,有错误的地方请大家指正,谢谢。
1.引入第三方库
//rxjava
implementation 'io.reactivex.rxjava2:rxjava:2.1.14-RC1'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
2.初始化
①创建okhttp
//设置缓存
File cacheDir = new File(MyApplication.getInstance().getCacheDir(), "my_okhttp_cache");
Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);
//log打印级别
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
//链接超时
.connectTimeout(10 * 1000, TimeUnit.MILLISECONDS)
//读取超时
.readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
//写入超时
.writeTimeout(60 * 1000, TimeUnit.MILLISECONDS)
//应用拦截器:打印日志
.addInterceptor(loggingInterceptor)
//设置缓存
.cache(cache)
.build();
②创建retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiService.HOST) //主地址
.addConverterFactory(GsonConverterFactory.create()) //直接解析成实体类
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
③创建请求接口类
public interface ApiService {
public static String HOST = "https://xxx/xxx/"; //注意要以斜杆结束
@FormUrlEncoded //表单请求要加上这个
@POST("xxx/xxxx")
Observable<ResponseBody> getSmsCode(@Field("mobilePhoneNumber") String phoneNumber);
//ResponseBody是okhttp提供的返回类,这里可用自己定义的实体类,与onNext()返回的结果对应
@Multipart //用于上传文件的表单请求
@POST("xxxx/xxxx/") Observable<ResponseBody> uploadImageFile(@Part MultipartBody.Part file); }
④请求
Api api = retrofit.create(Api.class);
api.getSmsCode(phoneNumber)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
Log.i("--onNext--",responseBody.string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
Log.i("--onError--",e.getMessage());
}
@Override
public void onComplete() {
}
});
onNext()为请求返回成功,在进入onComplete(),onError()表示失败并与onComplete()互斥。
⑤至此,一个完整的网络请求已经结束。不过本人对此有以下建议:
1.最好将retrofit封装起来
2.要使用CompositeDisposable快速解除订阅