转自:http://ranseti.top/article/retrofit2addrxjava2
项目需要compile的资源有
compile 'com.squareup.retrofit2:retrofit:2.3.0'
Retrofit2https://github.com/square/retrofit
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
retrofit2的Rxjava2适配器https://github.com/square/retrofit/tree/master/retrofit-adapters/rxjava2
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
Retrofit2的数据转换器https://github.com/square/retrofit/tree/master/retrofit-converters/gson
以上三个需要保持版本一致,除此还需要
compile 'com.google.code.gson:gson:2.8.2'
google的Gsonhttps://github.com/google/gson
compile "io.reactivex.rxjava2:rxjava:2.1.8"
Rxjavahttps://github.com/ReactiveX/RxJava
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
RxAndroidhttps://github.com/ReactiveX/RxAndroid
compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
okHttp的log拦截器,方便调试https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
下面直接看代码
- okHttp的配置
public class OkHttpConfigure {
private static final long TIMEOUT = 30;
public static OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("okHttp", message);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.build();
}
2.Retrofit配置(我的Demo中用了三个Host主机,所以配置了三个)
public class RetrofitConfigure {
/**
* GitHub配置
*/
private static final String GitHub_Host = "https://api.github.com";
public static Retrofit githubRetrofit = new Retrofit.Builder()
.baseUrl(GitHub_Host)
.client(OkHttpConfigure.httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
/**
* 物流100配置
*/
private static final String WuLiu_Host = "http://www.kuaidi100.com";
public static Retrofit wuLiuRetrofit = new Retrofit.Builder()
.baseUrl(WuLiu_Host)
.client(OkHttpConfigure.httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
/**
* 图片下载
*/
private static String picture_Host = "https://timgsa.baidu.com";
public static void setPicture_Host(String picture_Host) {
RetrofitConfigure.picture_Host = picture_Host;
}
public static Retrofit pictureRetrofit = new Retrofit.Builder()
.baseUrl(picture_Host)
.client(OkHttpConfigure.httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
3.GitHub的Api
public interface GitHubAPI {
//https://api.github.com/repos/square/retrofit/contributors
@GET("/repos/{owner}/{repo}/contributors")
Observable> getContributors(@Path("owner") String owner,
@Path("repo") String repo);
@GET("/timg?image&quality=80&size=b9999_10000&sec=1517483557140&di=8ef2706c558749c2c9ae999e4401651d&imgtype=0&src=http%3A%2F%2Fimg5.niutuku.com%2Fphone%2F1301%2F5651%2F5651-niutuku.com-446980.jpg")
Observable getcontributorsAvator();
// !!! 当心大文件,当是大文件时
@Streaming
@GET
Observable downloadFileWithDynamicUrlAsync(@Url String fileUrl);
}
4.创建API的实例,定制Observer实现数据的异步获取
public class ConnectHttp {
//创建 GitHub API 接口的一个实例。
public static GitHubAPI getGitHubAPI() {
return RetrofitConfigure.githubRetrofit.create(GitHubAPI.class);
}
//创建 WuLiu API 口的一个实例。
public static WuLiuAPI getWuLiuAPI() {
return RetrofitConfigure.wuLiuRetrofit.create(WuLiuAPI.class);
}
//创建 WuLiu API 口的一个实例。
public static GitHubAPI getPictureAPI() {
return RetrofitConfigure.pictureRetrofit.create(GitHubAPI.class);
}
/**
* 连接网络
* @param observable
* @param baseObserver
*/
public static void connect(Observable observable, BaseObserver baseObserver) {
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((baseObserver));
}
}
5.抽取观察者,对一些异常进行异常处理
public abstract class BaseObserver implements Observer {
private Context context;
public BaseObserver(Context context) {
this.context = context;
}
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull T t) {
Log.i("observer",new Gson().toJson(t));
onResponse(t);
}
public abstract void onResponse(T t);
@Override
public void onError(@NonNull Throwable e) {
Log.e("Observer",new Gson().toJson(e));
if (!NetWorkUtils.isNetworkConnected(context)) {
// NetWorkSetDialog.showSetNetworkUI(context);
Toast.makeText(context, "没有可用的网络", Toast.LENGTH_LONG).show();
}
if (e.getMessage().contains("404")) {
Toast.makeText(context, "网络404错误", Toast.LENGTH_LONG).show();
}
if (e.getMessage().contains("500")) {
Toast.makeText(context, "网络500错误", Toast.LENGTH_LONG).show();
}
if(e instanceof IllegalStateException){
Toast.makeText(context, "数据解析异常", Toast.LENGTH_LONG).show();
}
if(e instanceof SocketTimeoutException){
Toast.makeText(context, "请求超时", Toast.LENGTH_LONG).show();
}
e.printStackTrace();
}
@Override
public void onComplete() {
Log.i("observable", "-----------已完成----------");
}
}
6.对API进行一次包装方便调用
public class GitHubAPIPackage {
/**
* 获取GitHub仓库贡献者
*
* @param owner
* @param repo
* @return
*/
public static Observable> getContributors(String owner, String repo) {
return ConnectHttp.getGitHubAPI().getContributors(owner, repo);
}
/**
* 下载头像
* @return
*/
public static Observable getcontributorsAvator() {
return ConnectHttp.getPictureAPI().getcontributorsAvator();
}
}
7.进行调用
/**
* 查询retrofit贡献者
*/
private void initData() {
ConnectHttp.connect(GitHubAPIPackage.getContributors("square", "retrofit"),
new BaseObserver>(context) {
@Override
public void onResponse(List contributors) {
//TODO 做你想做的
}
});
}
详细Demo参考https://github.com/heyl1989/Retrfit2AddRxJava2