在平日的开发中,我们用后台写好给我们接口去获取数据。虽然我们有一些请求接口的工具,可以快速的拿到返回数据。但是在一些异常情况的处理上就不太方便了。我列出以下几个痛点:
快速的查看返回数据与数据的处理。(一般我们都是将写好的代码跑到手机上,点击到对应页面的对应按钮)
异常信息的返回与处理。比如一个接口返回一个列表数据,如果列表为空呢?(找后台给我们模拟数据)网速不好呢?(不知道怎么搞…)网络异常呢?(关闭网络)
后台有部分接口没有写好,你就只能等他了。
不知道上面的这三点有没有戳到你的痛处。如果扎心了,那么老铁你就有必要掌握今天的内容。
1.请求接口
我们就使用网络请求三件套(retrofit + okhttp + rxjava2)来举例。
首先添加一下依赖,同时记得加网络权限。
//RxJava
compile 'io.reactivex.rxjava2:rxjava:2.1.7'
//RxAndroid
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//okhttp
compile "com.squareup.okhttp3:okhttp:3.9.1"
//Retrofit
compile ("com.squareup.retrofit2:retrofit:2.3.0"){
exclude module: 'okhttp'
}
compile ("com.squareup.retrofit2:adapter-rxjava2:2.3.0"){
exclude module: 'rxjava'
}
compile "com.squareup.retrofit2:converter-gson:2.3.0"
测试接口:
public interface GithubApi {
String BASE_URL = "https://api.github.com/";
@GET("users/{username}")
Observable getUser(@Path("username") String username);
}
Retrofit的初始化,我们使用LoggingInterceptor来打印返回数据。
public class GithubService {
private static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GithubApi.BASE_URL)
.client(getOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
public static GithubApi createGithubService() {
return retrofit.create(GithubApi.class);
}
private static OkHttpClient getOkHttpClient(){
return new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
}
}
测试代码:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 23)
public class ResponseTest {
@Before
public void setUp() {
ShadowLog.stream = System.out;
initRxJava2();
}
private void initRxJava2() {
RxJavaPlugins.reset();
RxJavaPlugins.setIoSchedulerHandler(new Function() {
@Override
public Scheduler apply(Scheduler scheduler) throws Exception {
return Schedulers.trampoline