2024年安卓最全Android OkHttp使用和源码详解,中高级Android大厂高频面试题

文末

架构师不是天生的,是在项目中磨练起来的,所以,我们学了技术就需要结合项目进行实战训练,那么在Android里面最常用的架构无外乎 MVC,MVP,MVVM,但是这些思想如果和模块化,层次化,组件化混和在一起,那就不是一件那么简单的事了,我们需要一个真正身经百战的架构师才能讲解透彻其中蕴含的深理。

移动架构师

系统学习技术大纲

一线互联网Android面试题总结含详解(初级到高级专题)

image

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

@Override public void enqueue(Callback responseCallback) {

synchronized (this) {

if (executed) throw new IllegalStateException(“Already Executed”);

executed = true;

}

transmitter.callStart();

client.dispatcher().enqueue(new AsyncCall(responseCallback));

}

client.dispatcher()返回Dispatcher,调用 Dispatcher 的 enqueue 方法,执行一个异步网络请求的操作。

Dispatcher 是 OkHttpClient 的调度器,是一种门户模式。主要用来实现执行、取消异步请求操作。本质上是内部维护了一个线程池去执行异步操作,并且在 Dispatcher 内部根据一定的策略,保证最大并发个数、同一 host 主机允许执行请求的线程个数等。

Dispatcher.enqueue


void enqueue(AsyncCall call) {

synchronized (this) {

readyAsyncCalls.add(call);

if (!call.get().forWebSocket) {

AsyncCall existingCall = findExistingCallWithHost(call.host());

if (existingCall != null) call.reuseCallsPerHostFrom(existingCall);

}

}

promoteAndExecute();

}

实际上就是使用线程池执行了一个 AsyncCall,而 AsyncCall 继承了 NamedRunnable,NamedRunnable 实现了 Runnable 接口,因此整个操作会在一个子线程(非 UI 线程)中执行。

NamedRunnable


/**

* Runnable implementation which always sets its thread name.

*/

public abstract class NamedRunnable implements Runnable {

protected final String name;

public NamedRunnable(String format, Object… args) {

this.name = Util.format(format, args);

}

@Override public final void run() {

String oldName = Thread.currentThread().getName();

Thread.currentThread().setName(name);

try {

execute();

} finally {

Thread.currentThread().setName(oldName);

}

}

protected abstract void execute();

}

在 run 方法中执行了 一个抽象方法 execute 这个抽象方法被 AsyncCall 实现。

AsyncCall.execute


@Override protected void execute() {

boolean signalledCallback = false;

transmitter.timeoutEnter();

try {

Response response = getResponseWithInterceptorChain();

signalledCallback = true;

responseCallback.onResponse(RealCall.this, response);

} catch (IOException e) {

if (signalledCallback) {

// Do not signal the callback twice!

Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);

} else {

responseCallback.onFailure(RealCall.this, e);

}

} finally {

client.dispatcher().finished(this);

}

}

从上面看出而真正获取请求结果的方法是在 getResponseWithInterceptorChain 方法中,从名字也能看出其内部是一个拦截器的调用链。

RealCall.getResponseWithInterceptorChain


Response getResponseWithInterceptorChain() throws IOException {

// Build a full stack of interceptors.

List interceptors = new ArrayList<>();

interceptors.addAll(client.interceptors());

interceptors.add(new RetryAndFollowUpInterceptor(client));

interceptors.add(new BridgeInterceptor(client.cookieJar()));

interceptors.add(new CacheInterceptor(client.internalCache()));

interceptors.add(new ConnectInterceptor(client));

if (!forWebSocket) {

interceptors.addAll(client.networkInterceptors());

}

interceptors.add(new CallServerInterceptor(forWebSocket));

Interceptor.Chain chain = new RealInterceptorChain(interceptors, transmitter, null, 0,

originalRequest, this, client.connectTimeoutMillis(),

client.readTimeoutMillis(), client.writeTimeoutMillis());

boolean calledNoMoreExchanges = false;

try {

Response response = chain.proceed(originalRequest);

if (transmitter.isCanceled()) {

closeQuietly(response);

throw new IOException(“Canceled”);

}

return response;

} catch (IOException e) {

calledNoMoreExchanges = true;

throw transmitter.noMoreExchanges(e);

} finally {

if (!calledNoMoreExchanges) {

transmitter.noMoreExchanges(null);

}

}

}

Interceptor:拦截器是一种强大的机制,可以监视、重写和重试调用。

每一个拦截器的作用如下:

  • BridgeInterceptor:主要对 Request 中的 Head 设置默认值,比如 Content-Type、Keep-Alive、Cookie 等。

  • CacheInterceptor:负责 HTTP 请求的缓存处理。

  • ConnectInterceptor:负责建立与服务器地址之间的连接,也就是 TCP 链接。

  • CallServerInterceptor:负责向服务器发送请求,并从服务器拿到远端数据结果。

  • RetryAndFollowUpInterceptor:此拦截器从故障中恢复,并根据需要执行重定向。如果呼叫被取消,它可能会引发IOException。

在添加上述几个拦截器之前,会调用 client.interceptors 将开发人员设置的拦截器添加到列表当中。

对于 Request 的 Head 以及 TCP 链接,我们能控制修改的成分不是很多。所以咱们了解 CacheInterceptorCallServerInterceptor

CacheInterceptor 缓存拦截器

======================

CacheInterceptor 主要做以下几件事情:

1、根据 Request 获取当前已有缓存的 Response(有可能为 null),并根据获取到的缓存 Response,创建 CacheStrategy 对象。

2、 通过 CacheStrategy 判断当前缓存中的 Response 是否有效(比如是否过期),如果缓存 Response 可用则直接返回,否则调用 chain.proceed() 继续执行下一个拦截器,也就是发送网络请求从服务器获取远端 Response。

3、如果从服务器端成功获取 Response,再判断是否将此 Response 进行缓存操作。

CacheInterceptor.intercept


@Override public Response intercept(Chain chain) throws IOException {

//根据 Request 获取当前已有缓存的 Response(有可能为 null),并根据获取到的缓存 Response

Response cacheCandidate = cache != null

? cache.get(chain.request())

: null;

//获取当前时间

long now = System.currentTimeMillis();

//创建 CacheStrategy 对象

//通过 CacheStrategy 来判断缓存是否有效

CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get();

Request networkRequest = strategy.networkRequest;

Response cacheResponse = strategy.cacheResponse;

if (cache != null) {

cache.trackResponse(strategy);

}

if (cacheCandidate != null && cacheResponse == null) {

closeQuietly(cacheCandidate.body()); // The cache candidate wasn’t applicable. Close it.

}

//如果我们被禁止使用网络,并且缓存不足,则失败。返回空相应(Util.EMPTY_RESPONSE)

if (networkRequest == null && cacheResponse == null) {

return new Response.Builder()

.request(chain.request())

.protocol(Protocol.HTTP_1_1)

.code(504)

.message(“Unsatisfiable Request (only-if-cached)”)

.body(Util.EMPTY_RESPONSE)

.sentRequestAtMillis(-1L)

.receivedResponseAtMillis(System.currentTimeMillis())

.build();

}

// 如果缓存有效,缓存 Response 可用则直接返回

if (networkRequest == null) {

return cacheResponse.newBuilder()

.cacheResponse(stripBody(cacheResponse))

.build();

}

//没有缓存或者缓存失败,则发送网络请求从服务器获取Response

Response networkResponse = null;

try {

//执行下一个拦截器,networkRequest

//发起网络请求

networkResponse = chain.proceed(networkRequest);

} finally {

//如果我们在I/O或其他方面崩溃,请不要泄漏cache body。

if (networkResponse == null && cacheCandidate != null) {

closeQuietly(cacheCandidate.body());

}

}

。。。

//通过网络获取最新的Response

Response response = networkResponse.newBuilder()

.cacheResponse(stripBody(cacheResponse))

.networkResponse(stripBody(networkResponse))

.build();

//如果开发人员有设置自定义cache,则将最新response缓存

if (cache != null) {

if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) {

// Offer this request to the cache.

CacheRequest cacheRequest = cache.put(response);

return cacheWritingResponse(cacheRequest, response);

}

//返回response(缓存或网络)

return response;

}

通过 Cache 实现缓存功能


通过上面缓存拦截器的流程可以看出,OkHttp 只是规范了一套缓存策略,但是具体使用何种方式将数据缓存到本地,以及如何从本地缓存中取出数据,都是由开发人员自己定义并实现,并通过 OkHttpClient.Builder 的 cache 方法设置。

OkHttp 提供了一个默认的缓存类 Cache.java,我们可以在构建 OkHttpClient 时,直接使用 Cache 来实现缓存功能。只需要指定缓存的路径,以及最大可用空间即可,如下所示:

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.connectTimeout(15, TimeUnit.SECONDS)//设置超时

拦截器

.addInterceptor(new Interceptor() {

@Override

public Response intercept(Chain chain) throws IOException {

return null;

}

})

//设置代理

.proxy(new Proxy(Proxy.Type.HTTP,null))

//设置缓存

//AppGlobalUtils.getApplication() 通过反射得到Application实例

//getCacheDir内置 cache 目录作为缓存路径

//maxSize 1010241024 设置最大缓存10MB

.cache(new Cache(AppGlobalUtils.getApplication().getCacheDir(),

1010241024));

Cache 内部使用了 DiskLruCach 来实现具体的缓存功能,如下所示:

/**

* Create a cache of at most {@code maxSize} bytes in {@code directory}.

*/

public Cache(File directory, long maxSize) {

this(directory, maxSize, FileSystem.SYSTEM);

}

Cache(File directory, long maxSize, FileSystem fileSystem) {

this.cache = DiskLruCache.create(fileSystem, directory, VERSION, ENTRY_COUNT, maxSize);

}

DiskLruCache 最终会将需要缓存的数据保存在本地。如果感觉 OkHttp 自带的这套缓存策略太过复杂,我们可以设置使用 DiskLruCache 自己实现缓存机制。

LRU:是近期最少使用的算法(缓存淘汰算法),它的核心思想是当缓存满时,会优先淘汰那些近期最少使用的缓存对象。采用LRU算法的缓存有两种:LrhCache和DisLruCache,分别用于实现内存缓存和硬盘缓存,其核心思想都是LRU缓存算法。

CallServerInterceptor 详解

========================

CallServerInterceptor 是 OkHttp 中最后一个拦截器,也是 OkHttp 中最核心的网路请求部分。

CallServerInterceptor.intercept


@Override public Response intercept(Chain chain) throws IOException {

//获取RealInterceptorChain

RealInterceptorChain realChain = (RealInterceptorChain) chain;

//获取Exchange

Exchange exchange = realChain.exchange();

Request request = realChain.request();

long sentRequestMillis = System.currentTimeMillis();

exchange.writeRequestHeaders(request);

boolean responseHeadersStarted = false;

Response.Builder responseBuilder = null;

if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {

if (“100-continue”.equalsIgnoreCase(request.header(“Expect”))) {

exchange.flushRequest();

responseHeadersStarted = true;

exchange.responseHeadersStart();

responseBuilder = exchange.readResponseHeaders(true);

}

if (responseBuilder == null) {

if (request.body().isDuplex()) {

exchange.flushRequest();

BufferedSink bufferedRequestBody = Okio.buffer(

exchange.createRequestBody(request, true));

request.body().writeTo(bufferedRequestBody);

} else {

// Write the request body if the “Expect: 100-continue” expectation was met.

BufferedSink bufferedRequestBody = Okio.buffer(

exchange.createRequestBody(request, false));

request.body().writeTo(bufferedRequestBody);

bufferedRequestBody.close();

面试复习路线,梳理知识,提升储备

自己的知识准备得怎么样,这直接决定了你能否顺利通过一面和二面,所以在面试前来一个知识梳理,看需不需要提升自己的知识储备是很有必要的。

关于知识梳理,这里再分享一下我面试这段时间的复习路线:(以下体系的复习资料是我从各路大佬收集整理好的)

  • 架构师筑基必备技能
  • Android高级UI与FrameWork源码
  • 360°全方面性能调优
  • 解读开源框架设计思想
  • NDK模块开发
  • 微信小程序
  • Hybrid 开发与Flutter

知识梳理完之后,就需要进行查漏补缺,所以针对这些知识点,我手头上也准备了不少的电子书和笔记,这些笔记将各个知识点进行了完美的总结:

Android开发七大模块核心知识笔记

《960全网最全Android开发笔记》

《379页Android开发面试宝典》

历时半年,我们整理了这份市面上最全面的安卓面试题解析大全
包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。

如何使用它?

1.可以通过目录索引直接翻看需要的知识点,查漏补缺。
2.五角星数表示面试问到的频率,代表重要推荐指数

《507页Android开发相关源码解析》

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

《960全网最全Android开发笔记》

[外链图片转存中…(img-JZi6n7o5-1715728262793)]

《379页Android开发面试宝典》

历时半年,我们整理了这份市面上最全面的安卓面试题解析大全
包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。

如何使用它?

1.可以通过目录索引直接翻看需要的知识点,查漏补缺。
2.五角星数表示面试问到的频率,代表重要推荐指数

[外链图片转存中…(img-8dVbB0yZ-1715728262793)]

《507页Android开发相关源码解析》

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 23
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值