Android开发Android开发经验谈Android技术知识

【okhttp】- 网络请求封装过程(源码分析)

2020-03-09  本文已影响0人  拔萝卜占坑

简介

okhttp和HttpURLConnection都是用于网络请求,但okhttp并不是在HttpURLConnection基础上进行封装的,okhttp利用socket编写的一套网络请求库。在功能上更加强大,在性能上也更加优越。同时使用也更加方便。

数据请求

String getRequst(String url) throws IOException {
     OkHttpClient client = new OkHttpClient();
     Request request = new Request.Builder()
             .url(url)
             .build();
     try (Response response = client.newCall(request).execute()) {
         return response.body().string();
     }
}
public static Response postRequst(String url, String json) throws IOException {
     MediaType JSON = MediaType.parse("application/json; charset=utf-8");
     OkHttpClient client = new OkHttpClient();
     RequestBody body = RequestBody.create(JSON, json);
     Request request = new Request.Builder()
             .url(url)
             .post(body)
             .build();
     Response response = client.newCall(request).execute();
     return response;
}

配置组装

创建任务

执行任务

okhttp使用拦截器链式调用完成网络请求,不同的拦截器完成不同的功能,同时我们可以自定义自己的拦截器,完成特定的功能。

OkHttpClient.Builder提供了两个方法添加自定义拦截器。至于区别,在后面使用到的时候讲解。

  1. addInterceptor
    保存在interceptors对象集合里
  2. addNetworkInterceptor
    保存在networkInterceptors对象集合里
拦截器

开始执行任务

Response response = chain.proceed(originalRequest);

getResponseWithInterceptorChain方法中创建很多任务拦截器,通过链式调用,直到所有拦截器执行完成。首先看一下这个方法里面拦截器添加顺序。
interceptors自定义拦截器 -> RetryAndFollowUpInterceptor -> BridgeInterceptor -> CacheInterceptor -> ConnectInterceptor -> networkInterceptors -> CallServerInterceptor。那么执行的顺序也相同。

RealInterceptorChain,持有所以的拦截器数组,原始的Request,Transmitter等,在proceed方法中调用拦截器中的intercept方法,并创建一个新RealInterceptorChain对象传递给拦截器。

返回结果

等所有拦截器执行完成,请求结果从最后一个拦截器依次返回。

上一篇 下一篇

猜你喜欢

热点阅读