}
}
checkProvider(provider);
Gson gson = new GsonBuilder()
.setDateFormat(“yyyy-MM-dd HH:mm:ss”)
.create();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(getClient(baseUrl, provider))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson));
Retrofit retrofit = builder.build();
retrofitMap.put(baseUrl, retrofit);
providerMap.put(baseUrl, provider);
return retrofit;
}
private boolean empty(String baseUrl) {
return baseUrl == null || baseUrl.isEmpty();
}
private OkHttpClient getClient(String baseUrl, NetProvider provider) {
if (empty(baseUrl)) {
throw new IllegalStateException(“baseUrl can not be null”);
}
if (clientMap.get(baseUrl) != null) {
return clientMap.get(baseUrl);
}
checkProvider(provider);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(provider.configConnectTimeoutSecs() != 0
? provider.configConnectTimeoutSecs()
: connectTimeoutMills, TimeUnit.SECONDS);
builder.readTimeout(provider.configReadTimeoutSecs() != 0
? provider.configReadTimeoutSecs() : readTimeoutMills, TimeUnit.SECONDS);
builder.writeTimeout(provider.configWriteTimeoutSecs() != 0
? provider.configReadTimeoutSecs() : readTimeoutMills, TimeUnit.SECONDS);
CookieJar cookieJar = provider.configCookie();
if (cookieJar != null) {
builder.cookieJar(cookieJar);
}
provider.configHttps(builder);
RequestHandler handler = provider.configHandler();
if (handler != null) {
builder.addInterceptor(new NetInterceptor(handler));
}
Interceptor[] interceptors = provider.configInterceptors();
if (!empty(interceptors)) {
for (Interceptor interceptor : interceptors) {
builder.addInterceptor(interceptor);
}
}
if (provider.configLogEnable()) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
}
OkHttpClient client = builder.build();
clientMap.put(baseUrl, client);
providerMap.put(baseUrl, provider);
return client;
}
private boolean empty(Interceptor[] interceptors) {
return interceptors == null || interceptors.length == 0;
}
private void checkProvider(NetProvider provider) {
if (provider == null) {
throw new IllegalStateException(“must register provider first”);
}
}
public Map<String, Retrofit> getRetrofitMap() {
return retrofitMap;
}
public Map<String, OkHttpClient> getClientMap() {
return clientMap;
}
}
- 2、实现NetProvider接口并注入
NetMgr就是一个Retrofit的实现类,然后NetProvider是一个接口,需要在外部去实现,然后注入。再看一下NetProvider的实现类BaseNetProvider
public class BaseNetProvider implements NetProvider {
private static final long CONNECT_TIME_OUT = 30;
private static final long READ_TIME_OUT = 180;
private static final long WRITE_TIME_OUT = 30;
@Override
public Interceptor[] configInterceptors() {
return null;
}
@Override
public void configHttps(OkHttpClient.Builder builder) {
}
@Override
public CookieJar configCookie() {
return null;
}
@Override
public RequestHandler configHandler() {
return new HeaderHandler();
}
@Override
public long configConnectTimeoutSecs() {
return CONNECT_TIME_OUT;
}
@Override
public long configReadTimeoutSecs() {
return READ_TIME_OUT;
}
@Override
public long configWriteTimeoutSecs() {
return WRITE_TIME_OUT;
}
@Override
public boolean configLogEnable() {
return BuildConfig.DEBUG;
}
private class HeaderHandler implements RequestHandler {
@Override
public Request onBeforeRequest(Request request, Interceptor.Chain chain) {
return chain.request().newBuilder()
.addHeader(“X-Auth-Token”, Constant.accessToken)
.addHeader(“Authorization”, “”)
.build();
}
@Override
public Response onAfterRequest(Response response, Interceptor.Chain chain)
throws IOException {
ApiException e = null;
if (401 == response.code()) {
throw new ApiException(“登录已过期,请重新登录!”);
} else if (403 == response.code()) {
throw new ApiException(“禁止访问!”);
} else if (404 == response.code()) {
throw new ApiException(“链接错误”);
} else if (503 == response.code()) {
throw new ApiException(“服务器升级中!”);
} else if (500 == response.code()) {
throw new ApiException(“服务器内部错误!”);
}
return response;
}
}
在BaseNetProvider中实现了连接、读、写超时的时间处理,与请求和返回数据的请求头部处理。然后需要在Application中去注入BaseNetProvider
NetMgr.getInstance().registerProvider(new BaseNetProvider());
- 3、Observable实现
首先实现一个UseCase的基类,处理公共的使用方法。通过调用NetMgr.getInstance().getRetrofit(BuildConfig.BaseUrl).create(getType())来获取ApiService的实例,然后提供了指定线程的基类方法。至于PagingReq是一个分页模型,方便分页接口的使用。
public abstract class UseCase {
//用于分页请求
protected PagingReq pagingReq = new PagingReq();
protected T ApiClient() {
return NetMgr.getInstance().getRetrofit(BuildConfig.BaseUrl).create(getType());
}
//指定观察者与被观察者线程
protected Observable.Transformer<T, T> normalSchedulers() {
return new Observable.Transformer<T, T>() {
@Override
public Observable call(Observable source) {
return source.onTerminateDetach().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
private Class getType() {
Class entityClass = null;
Type t = getClass().getGenericSuperclass();
Type[] p = ((ParameterizedType) t).getActualTypeArguments();
entityClass = (Class) p[0];
return entityClass;
}
}
此处实现一个简单的获取城市信息的接口。 首先定义接口ApiService,然后实现获取Observable的方法
public class GetCitiesCase extends UseCase<GetCitiesCase.Api> {
interface Api {
@GET(“api/china/”)
Observable<List> getCitiesCase();
}
最后
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。
因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门**
如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!