手撸丐中丐版OkHttp

手撸丐中丐版OkHttp

通过简单实现的方式来加深框架的理解,在实现过程中思考源码是怎么实现的,为什么这么做。

Request 和 Response

根据网络的基础,首先创建Request请求和Response响应两个基础类。

Request包含请求地址,请求头,请求方式(GET/POST等)。支持设置请求地址,其他参数直接给填充上。

public class Request {
    final Map<String, String> headers;
    final String url;
    final String method;

    public Request(String url) {
        this.url = url;
        this.method = "GET";
        this.headers = new HashMap<>();
        this.headers.put("Content-Type", "application/json;charset=UTF-8");
    }

}

Response包含发起请求的Request信息,响应头,响应状态码和结果。

public class Response {
    final Request request;
    final Map<String, String> headers;
    final int code;
    final String message;

    public Response(Request request) {
        this.request = request;
        this.headers = new HashMap<>();
        this.headers.put("Content-Type", "application/json;charset=UTF-8");
        this.code = 200;
        this.message = "Success";
    }
}

创建一个Call接口,当前只包含一个execute方法,用来执行Request并返回结果。

public interface Call {

    Response execute(Request request);

}

创建一个Activity用来测试流程。

  1. 实现Call接口
  2. 创建请求对象
  3. 使用call.execute执行请求,返回对象
    public class HttpTestActivity extends AppCompatActivity {
    
        public static final String TAG = "HttpTestActivity";
        private TextView tvResponse;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_http);
            final Call call = new Call() {
                @Override
                public Response execute(Request request) {
                    return new Response(request);
                }
            };
            tvResponse = findViewById(R.id.tv_response);
            findViewById(R.id.btn_request).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Response response = call.execute(new Request("http://www.baidu.com"));
                    Log.e(TAG, response.toString());
                    tvResponse.setText(response.toString());
                }
            });
    
        }
    }

查看控制台打印的结果

Response{
    request=Request{
    headers={Content-Type=application/json;charset=UTF-8},
     url='http://www.baidu.com,
     method='GET
    },
     headers={Content-Type=application/json;charset=UTF-8},
     code=200,
     message='Success
    }

我们首先打通了这条路,实现了单机版的同步请求。接下来对流程上的每一项进行填充,实现异步执行,拦截器等功能。

异步任务

早在Android4.X时代,谷歌官方就禁止了在主线程中执行网络请求。所以一个网络请求框架必须要具备异步请求的功能。

首先改造接口类call,增加enqueue方法,让请求放入任务队列中等待执行。此外由于是异步操作,需要定义回调接口。

//回调接口
public interface Callback {

    void onResponse(Response response);
}


public interface Call {

    Response execute(Request request);

    void enqueue(Request request,Callback callback);
}

接下来定义线程池,进行入队任务的处理。在源码中线程池定义在Dispatch类中进行所有任务的管理,由于是丐中丐,直接创建RealCall类将线程池定义在此。

public class RealCall implements Call {

    public static final String TAG = "RealCall";
    private @Nullable
    ExecutorService executorService;

    public synchronized ExecutorService executorService() {

        if (executorService == null) {
            executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>());
        }
        return executorService;
    }

    @Override
    public Response execute(Request request) {
        return new Response(request);
    }

    @Override
    public void enqueue(final Request request, final Callback callback) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //打印线程信息
                Log.e(TAG, "run: " + Thread.currentThread().getName());
                try {
                    //模拟网络请求耗时
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                callback.onResponse(new Response(request));
            }
        };
        executorService().execute(runnable);
    }
}

我们的网络请求往往是短暂的,次数较多的任务。所以采用的是与Executors.newCachedThreadPool()一致的设置,源码中设置了线程工厂用来设置线程的名字。在Activity中点击按钮触发测试。会在不同的线程执行任务。

      call.enqueue(new Request("http://www.baidu.com"), new Callback() {
                @Override
                public void onResponse(Response response) {
                    Log.e(TAG, response.toString());
                }
            });

    --------------------------------
    E/RealCall: run: pool-1-thread-1
    E/RealCall: run: pool-1-thread-2
    E/RealCall: run: pool-1-thread-3
    E/RealCall: run: pool-1-thread-4
    E/RealCall: run: pool-1-thread-4
    E/RealCall: run: pool-1-thread-3
    E/RealCall: run: pool-1-thread-2
    E/RealCall: run: pool-1-thread-3
    E/RealCall: run: pool-1-thread-2

拦截器的实现

在源码中分别有interceptors 和 networkInterceptors 两块拦截器,分别代表网络请求前对Request进行处理和在请求后对响应结果Response进行处理。

public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory {

  final List<Interceptor> interceptors;
  final List<Interceptor> networkInterceptors;
}

在实际场景中,我们会对OkHttpClient设置统一的token信息,在请求完成后对结果进行打印。接下来就通过责任链模式来实现拦截器。

仿造源码实现拦截器接口类

public interface Interceptor {

    Response intercept(Chain chain);

    interface Chain {
        Request request();

        Response proceed(Request request);
    }
}

定义处理Request,执行网络请求(用Request获取Response),处理Response三种类型的拦截器。

public static class NetWorkInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) {
        // 执行网络请求,先执行之前对request的处理,调用AddParamsInterceptor
        chain.proceed(chain.request());
        try {
            //模拟网络请求耗时
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Response(chain.request());
    }
}

public static class AddParamsInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) {
        // 对Request进行处理
        Request request = chain.request();
        request.headers.put("token", "SElLIFlpTWpGbEcwSVQ1dit1Wm86ejdCbUhFVnRrcTFTV0FPWGNMVWJuZDF0ekY4dHpRbUkwRys1V21DMXYvWT06MTU4NTY1MjYyMjQ0NA==");
        return chain.proceed(request);
    }
}

public static class LoggerInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) {
    
        Response response = chain.proceed(chain.request());
        //对response进行操作,先之前网络请求前的request
        Log.e(TAG, "intercept: " + response.toString());
        return response;
    }
}

改写enqueue为责任链调用。

@Override
public void enqueue(final Request request, final Callback callback) {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //打印线程信息
            Log.e(TAG, "run: " + Thread.currentThread().getName());


            // 请求发起者
            Interceptor.Chain next = new Interceptor.Chain() {
                @Override
                public Request request() {
                    return request;
                }

                @Override
                public Response proceed(Request request) {
                    return null;
                }
            };

            for (final Interceptor interceptor : interceptors) {
                final Interceptor.Chain finalNext = next;
                Interceptor.Chain chain = new Interceptor.Chain() {
                    @Override
                    public Request request() {
                        return finalNext.request();
                    }

                    @Override
                    public Response proceed(Request request) {
                        return interceptor.intercept(finalNext);
                    }
                };
                next = chain;
            }

            callback.onResponse(next.proceed(request));
        }
    };
    executorService().execute(runnable);
}

责任链这块的实现写了很久,这种设计模式平时是真没用过。关联了下事件分发机制大概好理解些。再者思考下树的遍历。

//先序遍历
find(Node root){
    System.out.println(root.value);
    find(root.left);
    find(root.right);
}

//中序遍历
find(Node root){
    find(root.left);
    System.out.println(root.value);
    find(root.right);
}

//后序遍历
find(Node root){
    find(root.left);
    find(root.right);
    System.out.println(root.value);
}

与上面三种状态的拦截器处理类似。

其他

优秀的框架肯定有优秀的封装,上面丐中丐只是梳理了异步请求与拦截器的实现与源码差距甚大,甚至根本没有走通网络。在OkHttpClient源码中使用了门面模式,来管理拦截器列表,分发实例,设置超时时间,管理连接池等,同时使用Builder模式实现默认参数设置与链式创建。
除以上设计模式以外需要掌握线程池的默认设置,为什么?如何管理连接池?

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容