Android OkHttp源码阅读详解一

这篇具有很好参考价值的文章主要介绍了Android OkHttp源码阅读详解一。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家
👉点击跳转到教程

前言:源码阅读基于okhttp:3.10.0

Android中OkHttp源码阅读二(责任链模式)

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

1、首先回顾OkHttp的使用

public class MainActivity extends RxActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * OkHttp的使用
     */
    private static void okHttpUseAction() {
        //通过构建者设计模式得到OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        //get请求 构建者模式拿到request
        Request request = new Request.Builder().url("https://www.baidu.com/").get().build();
        //Call  call = RealCall
        Call call = okHttpClient.newCall(request);
//        call.cancel();//取消请求
        //同步方法,我们需要自己开启子线程 耗时
//        try {
//            Response response = call.execute();
//            String string = response.body().string();
//            InputStream inputStream = response.body().byteStream();
//            Reader reader = response.body().charStream();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //异步方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败...");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                System.out.println("请求完成:" + string);
//                InputStream inputStream = response.body().byteStream();
//                Reader reader = response.body().charStream();
            }
        });
    }

    public static void main(String[] args) {
        okHttpUseAction();
    }
}

2、OkHttp源码阅读之线程池详解

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 线程池的使用
 */
public class MyThreadPool {
    public static void main(String[] args) {
        //比较耗性能,开启子线程,然后回收
        new Thread() {
            @Override
            public void run() {
                super.run();
            }
        }.start();
        //java 1.5 线程如何复用  线程池复用
        //子线程
        //需要一份工作:招聘工作,员工完成工作后,解聘
        //需要一份工作:招聘工作,员工完成工作后,解聘
        //需要一份工作:招聘工作,员工完成工作后,解聘

        //线程池相当于以下
        //需要一份工作:招聘工作,员工完成工作后,继续执行其他工作,解雇

        //java 1.5 线程池复用,线程池(线程,如何让这么多线程复用,线程管理工作)
        //Executor
        //    --ExecutorService
        //        --AbstractExecutorService
        //          --ThreadPoolExecutor
        //ThreadPoolExecutor 学习此类

        //线程池里面,只有一个核心线程在跑任务
        /**
         * corePoolSize:核心线程数
         * maximumPoolSize:线程池非核心线程数,线程池规定大小
         * keepAliveTime:时间数值
         * unit:时间单位
         *       参数三和四作用:正在执行的任务Runnable 20 大于核心线程数  参数三和参数四才会起作用
         *       作用:Runnable1执行完毕后闲置60s,如果过了闲置60s,会回收掉Runnable1,如果在闲置时间60s内,复用此线程Runnable1
         * workQueue:队列
         *            作用:会把超出的任务加入到队列中,缓存起来
         */
//        ExecutorService executorService = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

        //Exception in thread "main" java.lang.IllegalArgumentException  会崩溃
//        ExecutorService executorService = new ThreadPoolExecutor(5,
//                1, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

//        ExecutorService executorService = new ThreadPoolExecutor(5,
//                10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

        //想实现缓存,线程池方案
        /**
         * corePoolSize:核心线程数
         * maximumPoolSize:最大线程数。线程池非核心线程数,线程池规定大小
         * keepAliveTime:时间数值
         * unit:时间单位
         *       参数三和四作用:正在执行的任务Runnable 20 大于核心线程数  参数三和参数四才会起作用
         *       作用:Runnable1执行完毕后闲置60s,如果过了闲置60s,会回收掉Runnable1,如果在闲置时间60s内,复用此线程Runnable1
         * workQueue:队列
         *            作用:会把超出的任务加入到队列中,缓存起来
         */
//        ExecutorService executorService = new ThreadPoolExecutor(0,
//                Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>());

        ExecutorService executorService = new ThreadPoolExecutor(0,
                Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread();
                        thread.setName("MyOkHttp Dispatcher");
                        thread.setDaemon(false);//不是守护线程
                        return thread;
                    }
                });

        for (int i = 0; i < 20; i++) { //循环第二次,闲置60s,复用上一次任务
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        System.out.println("当前线程,执行耗时任务,线程是:" + Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }


        /**************************************JAVA提供了API***********************************************/

        //Java设计者考虑到了不用使用线程池的参数配置,提供了API
        ExecutorService executorService1 = Executors.newCachedThreadPool();
        executorService1.execute(new Runnable() {
            @Override
            public void run() {

            }
        });

        //线程池里面只有一个核心线程,最大线程也只有一个
        ExecutorService executorService2 = Executors.newSingleThreadExecutor();

        Executors.newFixedThreadPool(5); //指定固定大小线程池
    }
}

3、守护线程详解

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 守护线程的使用
 */
public class MyThread {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                while (true) {
//                    try {
//                        Thread.sleep(10);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    } finally {
//                        System.out.println("run...");
//                    }
                    System.out.println("run...");
                }
            }
        };
        //守护线程
        thread.setDaemon(true);
        thread.start();
        //JVM main()所持有的进程该结束了
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

4、根据OkHttp中构建者模式写一个例子
1.定义一个类HomeParam

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 房子的图纸
 */
public class HomeParam {
    private double width;
    private double height;
    private String color = "白色";

    public HomeParam() {
    }

    public HomeParam(double width, double height, String color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "画出来的图纸:HomeParam{" +
                "width=" + width +
                ", height=" + height +
                ", color='" + color + '\'' +
                '}';
    }
}

2.定义一个类House

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 真实存在的房子
 */
public class House {
    private double width;
    private double height;
    private String color;

    public House() {
    }

    public House(double width, double height, String color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "具体建造出来的房子:House{" +
                "width=" + width +
                ", height=" + height +
                ", color='" + color + '\'' +
                '}';
    }
}

3、定义一个类Worker

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 工人开始建造房子
 */
public class Worker {
    //拿到图纸
    private HomeParam mHomeParam;

    public void setHomeParam(HomeParam homeParam) {
        mHomeParam = homeParam;
    }

    //工作,盖房子
    public House buildHouse() {
        House house = new House();
        house.setHeight(mHomeParam.getHeight());
        house.setWidth(mHomeParam.getWidth());
        house.setColor(mHomeParam.getColor());
        return house;
    }
}

4、定义一个类DesignerPerson

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 设计师
 */
public class DesignerPerson {
    private HomeParam mHomeParam;
    private Worker mWorker;

    public DesignerPerson() {
        mHomeParam = new HomeParam();
        mWorker = new Worker();
    }

    /**
     * 增加楼层
     *
     * @param height 高度
     */
    public DesignerPerson addHeight(double height) {
        mHomeParam.setHeight(height);
        return this;
    }

    /**
     * 增加宽度
     *
     * @param width 宽度
     */
    public DesignerPerson addWidth(double width) {
        mHomeParam.setWidth(width);
        return this;
    }

    /**
     * 增加颜色
     *
     * @param color 颜色
     */
    public DesignerPerson addColor(String color) {
        mHomeParam.setColor(color);
        return this;
    }

    /**
     * 把图纸给工人
     * 员工说房子盖好了
     *
     * @return
     */
    public House build() {
        mWorker.setHomeParam(mHomeParam);
        return mWorker.buildHouse();
    }
}

5.定义一个类UserClient

/**
 * @Author: ly
 * @Date: 2023/9/3
 * @Description: 用户有一个需求盖房子
 */
public class UserClient {
//    public static void main(String[] args) {
    //第一版

    //找到建筑公司
//        DesignerPerson designerPerson = new DesignerPerson();
//        designerPerson.addHeight(4);
//        designerPerson.addWidth(120.0);
//        designerPerson.addColor("绿色");
//
//        designerPerson.addHeight(2);
//        designerPerson.addWidth(100.0);
//        designerPerson.addColor("红色");
//
//        designerPerson.addHeight(3);
//        designerPerson.addWidth(90.0);
//        designerPerson.addColor("黄色");
//
//        //复制的过程
//
//        House house = designerPerson.build();
//        System.out.println(house);
//    }

    public static void main(String[] args) {
        //第二版,链式调用
        House house = new DesignerPerson().addColor("白色")
                .addWidth(100)
                .addHeight(8)
                .build();
        System.out.println(house);
    }
}

2、OkHttp主线流程源码阅读文章来源地址https://www.toymoban.com/news/detail-692641.html

1.OSI七层模型,TCP/IP模型(四层),HTTP格式
  OSI七层参考模型  --> TCP/IP参考模型
  TCP/IP参考模型四层:
  应用层 --> HTTP,HTTPS
  传输层 --> Socket

  HTTP get(请求行,请求属性集) post(请求行,请求属性集,type(form表单提交,还是其他提交),len(长度)==请求体)

2.OkHttp源码的主线流程
OkHttp的使用

OkHttpClient 通过构建者设计模式得到OkHttpClient
Request  通过构建者设计模式得到Request
Call  实际得到的是final class RealCall implements Call
//异步方法
call.enqueue(new Callback()
//不能执行大于1次 enqueue 否则会抛出异常Exception in thread "main" java.lang.IllegalStateException: Already Executed
synchronized (this) {
      if (executed) throw new IllegalStateException("Already Executed");
      executed = true;
    }
//拿到调度器dispatcher执行enqueue()方法
client.dispatcher().enqueue(new AsyncCall(responseCallback));

Dispatcher{
 /** Ready async calls in the order they'll be run. */  等待队列
  private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();

   运行的队列
  /** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
  private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();

  //最终会调用到Dispatcher类中的enqueue()方法
  synchronized void enqueue(AsyncCall call) {
      //同时运行的异步任务小于64&&同时访问(同一个)的服务器,不能超过5个  条件满足加入到运行队列中,然后执行
      if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
        runningAsyncCalls.add(call);
        executorService().execute(call); //执行
      } else {
        //加入到等待队列
        readyAsyncCalls.add(call);
      }
    }

  Deque双端队列:Deque(双端队列)是一种用于管理HTTP请求和响应拦截器的数据结构。
                Deque是"Double-ended Queue"的缩写,表示它可以在两端进行元素的插入和删除操作。

  AsyncCall 执行耗时任务
           signalledCallback 为true:这个错误是用户造成的,和OkHttp没有关系
                             为false:这个错误是OkHttp造成的。 onFailure

}

梳理主线流程:
OkHttpClient --> Request -> newCall  RealCall.enqueue(){不能重复执行} --> Dispatcher.enqueue(AsyncCall)-->
Dispatcher{if:先加入运行队列里面去,执行异步任务 else 直接加入等待队列} --> 异步任务 AsyncCall.execute()

分析OkHttp里面的线程池
executorService().execute(call);

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;
}
分析结果:OkHttp里面的线程池,采用的是缓存方案+线程工厂 name  不是守护线程
总结:采用的是缓存方案+定义线程工程(设置线程名,设置不是守护线程)
缓存方案:参数1 == 0
         参数2 == Integer.MAX_VALUE
         参数3 == 60s闲置时间,只要Runnable > 大于参数1  起作用(60s 之内就会复用之前的任务,60s之内就会回收任务)

--------------------------------->
看OkHttp源码,发现OkHttp里面使用了构建者设计模式,所以才要学习构建者设计模式
OkHttpClient ---构建者模式
Request      ---构建者模式
开始学习构建者设计模式 -->盖房子的例子(根据OkHttp源码中的链式调用优化)

到了这里,关于Android OkHttp源码阅读详解一的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Android OkHttp 源码浅析一

    演进之路:原生Android框架不好用 ---- HttpUrlConnect   和 Apache HTTPClient   第一版  底层使用HTTPURLConnect   第二版 Square构建 从Android4.4开始 基本使用: 同步方法,Deque 双向队列 executableCalls 添加到calls 然后取出遍历 执行 executeOn runningAsyncCalls 正在执行的Call    for (i in 0 until e

    2024年02月11日
    浏览(30)
  • Android OkHttp源码分析--分发器

    OkHttp是当下Android使用最频繁的网络请求框架,由Square公司开源。Google在Android4.4以后开始将源码中 的HttpURLConnection底层实现替换为OKHttp,同时现在流行的Retrofit框架底层同样是使用OKHttp的。 OKHttp优点: 1、支持Http1、Http2、Quic以及WebSocket; 2、连接池复用底层TCP(Socket),减少请求

    2024年02月13日
    浏览(32)
  • Android---OkHttp详解

    OkHttp 是一套处理 HTTP 网络请求的依赖库,由 Square 公司设计研发并开源,目前可以在 Java 和 Kotlin 中使用。对于 Android App,OkHttp 现在几乎已经占据了所有的网络请求操作。 RetroFit + OkHttp 实现网络请求似乎成了一种标配。 因此,它也是每个 Android 开发工程师的必备技能。了解

    2024年01月19日
    浏览(31)
  • Android Okhttp3 分发器源码解析

    在 OkHttp 中,分发器(Dispatcher)是负责调度和执行网络请求的组件。它 管理 着 并发 的 请求数量 以及请求的 优先级 ,确保合理地使用底层的连接池和线程池,从而 提高 网络请求的 效率 和 性能 。 默认情况下,OkHttp 使用一个单例的分发器,它可以处理同时进行的最大请求

    2024年02月12日
    浏览(37)
  • Android 使用okhttp监控网络数据

    这里使用Okhttp写了一个demo来监听网络请求过程中的一系列数据,包括当前网络类型、请求体、响应体大小,url,请求方式,当然还有本次核心获取域名解析时长,建立连接时长,保持连接时长,请求总时长这些数据。 一次网络请求经历了哪些过程 通过域名访问的方式来请求

    2024年02月11日
    浏览(34)
  • Android OKhttp使用(下载和上传文件)

    首先在build.gradle中引入okhttp 下面是demo(用okthttp下载网络上的资源) 用okthttp将资源上传至网络

    2024年02月11日
    浏览(39)
  • Android - OkHttp 访问 https 的怪问题

    最近使用 OkHttp 访问 https 请求时,在个别 Android 设备上遇到了几个问题,搜罗网上资料,经过一番实践后,问题得到了解决,同时,我也同步升级了我的 https 证书忽略库 ANoSSL ,在此,对搜集到的资料和问题解决方案做个记录。 文章中的代码实现可到 GitHub 仓库中自行获取:

    2024年04月29日
    浏览(21)
  • [Android]网络框架之OkHttp(详细)(kotlin)

    目录 OkHttp的介绍 添加依赖 OkHttp的使用 get的同步与异步请求 post的同步与异步请求 POST请求的数据格式 POST请求上传文件 POST请求上传json对象 POST请求上传多个数据 OkHttp的配置 1.Builder构建器 2.自定义拦截器 3.自定义缓存 4. 自定义Cookie https://square.github.io/okhttp/ 由Square公司贡献的

    2024年02月12日
    浏览(73)
  • Android低版本(4.4)okhttp 网络适配

    目录 访问网络时,出现错误: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb7eabc88: Failure in SSL library, usually a protocol error    error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (external/openssl/ssl/s23_clnt.c:741 0xa4fb8d5c:0x00000000) SSLSocket的setEnabledProtocols配置支持TLSv1.1,

    2024年01月17日
    浏览(29)
  • 【Android】OkHttp+Retrofit+Flow的简单使用

    实现一个简单的登录功能 引入依赖 我们现在有这样一个 Body 请求参数 当使用 post 请求之后,获取返回的数据 当允许登录的话,这个值就是 true 我们先创建两个数据Bean类 然后我们再创建一个密封类处理返回结果的分类 我们再创建一个Retrofit+OkHttp的单例类 好了,接下来再创

    2024年02月12日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包