Android开发老生新谈:从OkHttp原理看网络请求,flutterui模板

“深入交流“系列:Okhttp(一)请求流程解析 Okhttp请求流程源码解析 前言 最近发现以前学习过的好多东西,都忘记了,所以打算复习一次,并且通过输出博客来加深印象。Okhttp准备分成两篇文章来讲解,这篇文章主要叙述一下Okhttp的整体请求流程,第二篇文章则讲述一下Okhttp中极为重要的拦截器。“深入交流”系列打算从一些第三方框架源码或者FrameWork层源码入手,进行"深入"的交流,会持续输出下去,敬请期待。 1、Okhttp的同步请求和异步请求 在分析Okhttp的源码之前,我们首先了解一下Okhttp最基本的实现一次网络请求的方式。 O 阅读详情

interceptors = interceptors,

index = 0,

exchange = null,

request = originalRequest,

connectTimeoutMillis = client.connectTimeoutMillis,

readTimeoutMillis = client.readTimeoutMillis,

writeTimeoutMillis = client.writeTimeoutMillis

)

…

try {

val response = chain.proceed(originalRequest)

…

return response

}

…

}

getResponseWithInterceptorChain()的内部实现是通过一个责任链模式来完成,将网络请求的各个阶段封装到各个链条中(即各个拦截器Interceptor),配置好各个Interceptor后将其放在⼀个List⾥,然后作为参数,创建⼀个RealInterceptorChain对象,并调⽤ chain.proceed(request)来发起请求和获取响应。

在每一条拦截器中,会先做一些准备动作,例如对该请求进行是否可用的判断,或者将请求转换为服务器解析的格式,等等,接着就对请求执行chain.proceed(request)。上面提到getResponseWithInterceptorChain()的内部实现是一个责任链模式,而chain.proceed(request)的作用就是责任链模式的核心所在,将请求移交给下一个拦截器。

OkHttp中连自定义拦截器包括在内,一共有7种拦截器,在这里,网络请求的细节就封装在各个拦截器中,每个拦截器也都有自己的职责,只要把每个拦截器研究清楚,整个网络请求也就明了了。下面就来一一分析这些拦截器的职责。

7种拦截器的职责


1、用户自定义拦截器interceptors

用户自定义拦截器是在所有其他拦截器之前,开发者可根据业务需求进行网络拦截器的自定义,例如我们常常自定义Token处理拦截器,日志打印拦截器等。

2、RetryAndFollowUpInterceptor

RetryAndFollowUpInterceptor是一个请求失败和重定向时重试的拦截器。它的内部开启了一个请求循环,每次循环都会先做一个准备动作(call.enterNetworkInterceptorExchange(request, newExchangeFinder)),这个准备动作最主要的目的在于创建一个ExchangeFinder,为请求寻找可用的Tcl或者Tsl连接以及设置跟连接相关的一些参数,如连接编码解码器等。 ExchangeFinder在后面网络连接时,会详细说明。

准备工作做好后便开始了一个网络请求(response = realChain.proceed(request)),这句代码的目的是为了将请求传递给下一个拦截器。同时,会判断当前请求是否会出错以及是否需要重定向。如果出错或者需要重定向,那么就又开始新一轮的循环,直到没有出错和需要重定向为止。

这里出错和重定向的判断标准也简单说一下:

  • 判断出错的标准: 利用try-catch块对请求进行异常捕获,这里会捕获RouteException和IOException,并且在出错后都会先判断当前请求是否能够进行重试的操作。

  • 重定向标准: 这里判断是否需要重定向,是对Response的状态码Code进行审查,当状态码为3xx时,则表示需要重定向,而后创建一个新的request,进行重试操作。

3、BridgeInterceptor

BridgeInterceptor是用来连接应用程序代码和网络代码的一个拦截器。也就是说该拦截器会帮用户准备好服务器请求所需要的一些配置。可能定义太抽象,我们就先来看一下一个请求Url所对应的服务器请求头是怎么样的?

URL: wanandroid.com/wxarticle/c…

方法: GET

那它所对应的请求头如下:

GET /wxarticle/chapters/json HTTP/1.1

Host: wanandroid.com

Accept: application/json, text/plain, /

Accept-Encoding: gzip, deflate, br

Accept-Language: zh-CN,zh;q=0.9

Connection: keep-alive

User-Agent: Mozilla/5.0 x

OkHttp3源码详解(一) Request类,2021年Android开发实战 HttpUrl主要用来规范普通的url连接,并且解析url的组成部分 现通过下面的例子来示例httpUrl的使用 https://www.google.com/search?q=maplejaw ①使用parse解析url字符串: HttpUrl url = HttpUrl.parse(“https://www.google.com/search?q=maplejaw”); ②通过构造者模式来常见: HttpUrl url = new HttpUrl.Builder() .scheme(“ 阅读详情

相关推荐

OkHttp3源码详解(一) Request类,从青铜到王者的路线

现通过下面的例子来示例httpUrl的使用q=maplejaw②通过构造者模式来常见:.build();``````````Headers用于配置请求头,对于请求头配置大家一定不陌生吧,比如User-Agent和`Cache-Control等等。还可以使用它的重载方法of(Map map)方法来创建(2)构建者模式创建:``````````````````````````.set(“name1”,“value1”)//set表示name1是唯一的,会覆盖掉已经存在的。

2301_82257317的博客 1081

STM32 CubeMX实战:手把手教你用I2C驱动IST8310磁力计(附完整代码)

本文详细介绍了如何使用STM32 CubeMX和I2C驱动IST8310磁力计,从硬件连接到代码实现的完整流程。重点讲解了I2C通信异常处理、传感器初始化序列优化以及中断驱动数据采集方案,帮助开发者快速搭建可靠的地磁场数据采集系统。

weixin_42531163的博客 189

【低空经济】无人机充电站设计方案

随着无人机技术的快速发展和广泛应用,其在物流、农业、巡检、救援等领域的应用日益普及。然而,无人机的续航能力一直是限制其大规模应用的关键因素之一。为了解决这一问题,无人机充电站的设计与建设显得尤为重要。本项目旨在设计一套高效、智能、可扩展的无人机充电站系统,以满足不同场景下无人机的充电需求,提升其作业效率和应用范围。无人机充电站的设计将围绕以下几个核心目标展开:首先,充电站应具备快速充电能力,以减少无人机的停机时间,提高作业效率;

2960

告别环境报错:Qt Creator里配置Android SDK/NDK/JDK路径的完整避坑指南

本文详细解析了在Qt Creator中配置Android SDK/NDK/JDK路径的完整避坑指南,深入探讨了路径检测的内部机制、构建套件配置的隐藏逻辑以及项目级与全局配置的优先级。通过实际案例和高级排查技巧,帮助开发者解决常见的环境报错问题,提升Qt安卓开发效率。

weixin_42548829的博客 238

医学图像中的小目标病灶检测难题:我的硕士研究总结与思考

医学图像中的小目标检测和分割,主要指在CT、MRI、超声等医学影像中识别和分割微小病灶或细小结构。这些小目标通常体积小、边界模糊、特征不明显,却往往是关键病灶,例如肺部小结节、脑微出血、乳腺微钙化等。

weixin_45638136的博客 2370

AD9361 官方例程

文章目录一、官方资料1.1 介绍1.2 下载 和 使用1.3 相关资料二、步骤2.1 在Vivado中构建HDL2.2 在SDK中构建No- OS总结 一、官方资料 1.1 介绍 HDL参考设计介绍:AD9361 HDL Reference Designs 无操作系统介绍:AD9361 No-OS Software 1.2 下载 和 使用 HDL下载:Download HDL 在Vivado中构建HDL:Building HDL No-OS下载:Download No-OS 1.3 相关资料 AD

weixin_44630490的博客 3万+

直流无刷BLDC六步换相“电流环”、“速度环”的关系

4、在电流闭环模式下,电机的电流严格按给定电流运行,负载大小变化时,电流不变,电机速度跟随负载非正常变化,例如速度严重“超速”时,需要“限速”保护,这个任务是“速度环”的,这时“速度环”会根据设定的速度上限,控制触发器,将电机速度迅速将下来,电流降下来,在“限速”保护期间,“电流环”失去对触发器的控制作用;3、在电流闭环模式下,电机的电流严格按给定电流运行,负载大小变化时,电流不变,电机速度跟随负载正常变化,“速度环”对速度大小的控制作用是没有的;6、很多人想当然,“电流环”不工作,电机“电流”哪里来的?

u011878611的博客 5472

数据分享|1961-2017年中国0.25°×0.25° 逐日地表水文数据集(VIC-CN05.1)

其中,全球径流中心(University of New Hampshire and Global Runoff Data Centre, UNH/GRDC)的复合产流场集成了观测的河道径流和水量平衡模式模拟的地表和地下径流,常被用来评估模拟的径流。在长白山、海北灌丛和千烟洲通量站,模拟与观测的逐月潜热通量的平均NSE为0.61。VIC-CN05.1受益于较准确的大气驱动场、先进的地表水文参数化方案以及更真实丰富的土壤信息,可作为中国水文气象研究的参照数据,用于陆面模式的评估和长期的趋势分析等。

J_Giser的博客 1834

[VT虚拟化驱动]安装DPC回调检测CPU对VT的支持

文章目录前言一、驱动基本框架二、安装DPC回调三、检测CPU对VT的支持本章代码def.h:DriverEntry.cpputil.cpp 前言 对于VT的介绍网上有很多详细的介绍,这里不再赘述,只需要知道它有比操作系统还高的权限,可以利用这一点进行某些操作,如内存隐藏, 无痕HOOK ,MSR HOOK, 调试或者反调试, 这里直奔主题 一、驱动基本框架 虚拟机设置里虚拟化引擎设置: 新建一个空的WDM工程,平台设置为x64平台,右键属性——>Inf2Cat——>Run Inf2Cat设置

吾无法无天的博客 3909

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: Android开发是简单的「能写应用就行」吗,android开发基础应用
下一篇: Android面试题精选:讲一讲-Android-的事件分发机制,程序员中年危机
flunsna
博客等级 码龄5年 10粉丝 98原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值