读书笔记——《Android进阶之光》

Android进阶之光——网络编程

2021-08-22  本文已影响0人  So_ProbuING

网络编程

网络分层

网络分层有不同的模型,有的分为7层,有的分为5层。


5层网络分层

TCP的三次握手与四次挥手

TCP传输

TCP三次握手与四次挥手的过程


三次握手与四次挥手

连接复用 keepalive connections

连接复用

HTTP协议原理

http://host[":"post][abs_path]

HTTP请求报文

请求报文的一般格式

HTTP响应报文

响应报文

源码解析OkHttp

OkHttp的请求网络流程

@Override
public Call newCall(Request request) {
return new RealCall(this, request);
}

可以看到实际返回的是一个RealCall类。我们调用enqueue异步请求网络实际上是调用RealCall的enqueue方法

void enqueue(Callback responseCallback, boolean forWebSocket) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
client.dispatcher().enqueue(new AsyncCall(responseCallback, forWebSocket));
}

从这可以看出最终的请求是dispatcher来完成的,我们来看看dispatcher

/** 最大并发请求数*/
private int maxRequests = 64;
/** 每个主机的最大请求数*/
private int maxRequestsPerHost = 5;
/** 消费者线程池 */
private ExecutorService executorService;
/** 将要运行的异步请求队列 */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
/**正在运行的异步请求队列 */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
/** 正在运行的同步请求队列 */
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();

来看Dispatcher的构造方法

public Dispatcher(ExecutorService executorService) {
this.executorService = executorService;
}
public Dispatcher() {
}
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60,
TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory
("OkHttp Dispatcher", false));
}
return executorService;
}

从dispathcer的构造方法中可以看到,dispathcer中持有一个线程池,这个线程池可以使用自己设定的线程池。如果没有设定线程池,则会在请求网络前自己创建默认线程池。这个线程池比较适合执行大量的耗时比较少的任务。来看它的enqueue方法

synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call)
< maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}

当正在运行的异步请求队列中的数量小于64并且正在运行的请求主机数小于5时,把请求加载到runningAsyncCalls中并在线程池中执行,否则就加入到readyAsyncCalls中进行缓存等待。
来看AsyncCall的execute方法

@Override
protected void execute() {
boolean signalledCallback = false;
try {
Response response = getResponseWithInterceptorChain(forWebSocket);//1
if (canceled) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
signalledCallback = true;
responseCallback.onResponse(RealCall.this, response);
}
} catch (IOException e) {
if (signalledCallback) {
logger.log(Level.INFO, "Callback failure for " + toLoggableString(), e);
} else {
responseCallback.onFailure(RealCall.this, e);
}
} finally {
client.dispatcher().finished(this);
}
}

我们可以看到 getResponseWithInterceptorChain方法返回了Response,这说明正在请求网络

private Response getResponseWithInterceptorChain(boolean forWebSocket)
throws IOException {
Interceptor.Chain chain = new ApplicationInterceptorChain(0, originalRequest,
forWebSocket);
return chain.proceed(originalRequest);
}

在这个方法中创建了ApplicationInterceptorChain。这是一个拦截器链,这个类也是RealCall的内部类,接下来执行了它的proceed方法

public Response proceed(Request request) throws IOException {
if (index < client.interceptors().size()) {
Interceptor.Chain chain = new ApplicationInterceptorChain(index + 1,
request, forWebSocket);
//从拦截器列表中取出拦截器
Interceptor interceptor = client.interceptors().get(index);
Response interceptedResponse = interceptor.intercept(chain);//1
if (interceptedResponse == null) {
throw new NullPointerException("application interceptor " + interceptor
+ " returned null");
}
return interceptedResponse;
}
return getResponse(request, forWebSocket);
}

可以看到proceed方法每次从拦截器列表中取出拦截器。当存在多个拦截器时都会//1处阻塞,并等待下一个拦截器的调用返回。


拦截器的使用场景

拦截器时一种能够监控、重写、重试调用的机制。拦截器用来添加、移除、转换请求和响应的头部信息。我们可以看到return getResponse(request,forWebSocket)如果没有更多拦截器的话,就会执行网络请求。

我们看下getResponse方法

Response getResponse(Request request, boolean forWebSocket) throws
IOException {
...
engine = new HttpEngine(client, request, false, false, forWebSocket,
null, null, null);
int followUpCount = 0;
while (true) {
if (canceled) {
engine.releaseStreamAllocation();
throw new IOException("Canceled");
}
boolean releaseConnection = true;
try {
engine.sendRequest();
engine.readResponse();
releaseConnection = false;
} catch (RequestException e) {
throw e.getCause();
} catch (RouteException e) {
...
}
}

在获取网络响应的方法中 我们可以看到创建了HttpEngine类,并调用了HttpEngine的sendRequest方法和readResponse方法

public void sendRequest() throws RequestException, RouteException, IOException {
if (cacheStrategy != null) return; // Already sent.
if (httpStream != null) throw new IllegalStateException();
Request request = networkRequest(userRequest);
//获取 client 中的 Cache, 同时 Cache 在初始化时会读取缓存目录中曾经请求过的所有信息
InternalCache responseCache = Internal.instance.internalCache(client);
Response cacheCandidate = responseCache != null
? responseCache.get(request): null;//1
long now = System.currentTimeMillis();
cacheStrategy = new CacheStrategy.Factory(now, request, cacheCandidate).
get();
//网络请求
networkRequest = cacheStrategy.networkRequest;
//缓存的响应
cacheResponse = cacheStrategy.cacheResponse;
if (responseCache != null) {
//记录当前请求是网络发起还是缓存发起
responseCache.trackResponse(cacheStrategy);
}
if (cacheCandidate != null && cacheResponse == null) {
closeQuietly(cacheCandidate.body());
}
//不进行网络请求并且缓存不存在或者过期, 则返回 504 错误
if (networkRequest == null && cacheResponse == null) {
userResponse = new Response.Builder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.protocol(Protocol.HTTP_1_1)
.code(504)
.message("Unsatisfiable Request (only-if-cached)")
.body(EMPTY_BODY)
.build();
return;
}
// 不进行网络请求而且缓存可以使用, 则直接返回缓存
if (networkRequest == null) {
userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.build();
userResponse = unzip(userResponse);
return;
}
//需要访问网络时
boolean success = false;
try {
httpStream = connect();
httpStream.setHttpEngine(this);
...
}
}

这里可以看出缓存是基于Map的 key就是请求中url的md5,value是在文件中查询到的缓存,页面置换基于LRU算法。

接着来看HttpEngine的readResponse方法

public void readResponse() throws IOException {
...
else{
//读取网络响应
networkResponse = readNetworkResponse();
}
receiveHeaders(networkResponse.headers());
if (cacheResponse != null) {
//检查缓存是否可用。 如果可用, 就用当前缓存的 Response,关闭网络连接,释放连接
if (validate(cacheResponse, networkResponse)) {//1
userResponse = cacheResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.headers(combine(cacheResponse.headers(), networkResponse.
headers()))
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
networkResponse.body().close();
releaseStreamAllocation();
InternalCache responseCache = Internal.instance.internalCache(client);
responseCache.trackConditionalCacheHit();
responseCache.update(cacheResponse, stripBody(userResponse));
userResponse = unzip(userResponse);
return;
} else {
closeQuietly(cacheResponse.body());
}
}
userResponse = networkResponse.newBuilder()
.request(userRequest)
.priorResponse(stripBody(priorResponse))
.cacheResponse(stripBody(cacheResponse))
.networkResponse(stripBody(networkResponse))
.build();
if (hasBody(userResponse)) {
maybeCache();
userResponse = unzip(cacheWritingResponse(storeRequest, userResponse));
}
}

这个方法主要用来解析HTTP响应报头,如果有缓存可用,则用缓存的数据并更新缓存,否则就用网络请求返回的数据


OkHttp的请求流程图

解析Retrofit

Retrofit是Square公司开发的一款针对Android网络请求的框架。Retrofit的底层是基于OkHttp实现的,它更多使用运行时注解的方式提供功能
我们在使用Retrofit请求网络时,首先需要写请求接口

public interface IpService {
@GET("getIpInfo.php?ip=59.108.54.37")
Call<IpModel> getIpMsg();

接着我们创建Retrofit

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();

可以看出来Retrofit是通过建造者模式构建出来的,我们看一下Builder方法做了什么

public Builder() {
this(Platform.get());
}
private static final Platform PLATFORM = findPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform findPlatform() {
try {
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("java.util.Optional");
return new Java8();
} catch (ClassNotFoundException ignored) {
}
try {
Class.forName("org.robovm.apple.foundation.NSObject");
return new IOS();
} catch (ClassNotFoundException ignored) {
}
return new Platform();
}

可以看到Platform的get方法最终调用的是findPlatform方法,会根据不同的运行平台来提供不同的线程池,接下来看build方法

public Retrofit build() {
if (baseUrl == null) {//1
throw new IllegalStateException("Base URL required.");
}
okhttp3.Call.Factory callFactory = this.callFactory;//2
if (callFactory == null) {
callFactory = new OkHttpClient();//3
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();//4
}
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.
adapterFactories);//5
adapterFactories.add(platform.defaultCallAdapterFactory
(callbackExecutor));
List<Converter.Factory> converterFactories = new ArrayList<>(this.
converterFactories);//6
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}

这里1处可看出baseUrl是必须指定的

Call的创建过程

我们创建Retrofit实例并调用如下代码来生成接口的动态代理对象

IpService ipService = retrofit.create(IpService.class);

我们看下Retrofit的create方法

public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[]
{ service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override
public Object invoke(Object proxy, Method method, Object... args)
throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod serviceMethod = loadServiceMethod(method);//1
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}

我们可以看到create方法返回了一个动态代理对象。当我们调用IpService的getIpMsg方法时,最终会调用InvocationHandler的invoke方法

上一篇下一篇

猜你喜欢

热点阅读