1.Okhttp请求流程:

Okhttp内部的大致请求流程图如下所示:

使用方式:

public class OkHttpUtils {private static String TAG = "OkHttpUtils";private static String url = "http://www.baidu.com";//OkHttp 异步get请求public static void OkHttpEnqueue() {OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(url).get()  //默认就是get请求  可以不写.build();final Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic void onResponse(Call call, Response response) throws IOException {}});}//OkHttp 同步get请求public static void okHttpSync() {OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(url).build();Call call = okHttpClient.newCall(request);new Thread(new Runnable() {@Overridepublic void run() {try {Response response = call.execute();Log.d(TAG, "run: " + response.body().string());} catch (Exception e) {e.printStackTrace();}}});}//OkHttp 异步post方式提交Stringpublic static void OkHttpPostEnqueue() {MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");String requestBody = "I am Jeled";OkHttpClient okHttpClient = new OkHttpClient();Request request = new Request.Builder().url(url).post(RequestBody.create(mediaType, requestBody)).build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Log.d(TAG, "onFailure:" + e.getMessage());}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());Headers header = response.headers();for (int i = 0; i < header.size(); i++) {Log.d(TAG, header.name(i) + ":" + header.value(i));}Log.d(TAG, "onResponse:" + response.body().string());}});}//OkHttp 异步post方式提交流public static void OkHttpPost() {RequestBody requestBody = new RequestBody() {@Nullable@Overridepublic MediaType contentType() {return MediaType.parse("text/x-markdown; charset=utf-8");}@Overridepublic void writeTo(BufferedSink sink) throws IOException {sink.writeUtf8("I am Jeled");}};Request request = new Request.Builder().url(url).post(requestBody).build();OkHttpClient okHttpClient = new OkHttpClient();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Log.d(TAG, "onFailure:" + e.getMessage());}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());Headers header = response.headers();for (int i = 0; i < header.size(); i++) {Log.d(TAG, header.name(i) + ":" + header.value(i));}Log.d(TAG, "onResponse:" + response.body().string());}});}//OkHttp 异步post方式提交文件public static void OkHttpPostFile() {MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");File file = new File("test.md");Request request = new Request.Builder().url(url).post(RequestBody.create(mediaType,file)).build();OkHttpClient okHttpClient = new OkHttpClient();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Log.d(TAG, "onFailure:" + e.getMessage());}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());Headers header = response.headers();for (int i = 0; i < header.size(); i++) {Log.d(TAG, header.name(i) + ":" + header.value(i));}Log.d(TAG, "onResponse:" + response.body().string());}});}//OkHttp 异步post方式提交表单public static void OkHttpPostForm() {RequestBody requestBody = new FormBody.Builder().add("search","Jurassic Park").build();Request request = new Request.Builder().url(url).post(requestBody).build();OkHttpClient okHttpClient = new OkHttpClient();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {Log.d(TAG, "onFailure:" + e.getMessage());}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());Headers header = response.headers();for (int i = 0; i < header.size(); i++) {Log.d(TAG, header.name(i) + ":" + header.value(i));}Log.d(TAG, "onResponse:" + response.body().string());}});}}

备注:以上就是Okhttp的get或是post的同步或异步的请求的简单使用

源码梳理:

1、拦截器:

  • 用户自定义拦截器:(继承Interceptor接口,实现intercept方法)

  • RetryAndFollowUpInterceptor:失败重试以及重定向拦截器

  • BridgeInterceterptor:桥接拦截器 (请求时,对必要的Header进行一些添加,接收响应时,移除必要的Header)

  • CacheInterceptor:缓存拦截

    1.根据request得到cache中缓存的response

    2.确认 request判断缓存的策略,是否要使用了网络,缓存或两者都使用

    3.调用下一个拦截器,决定从网络上来得到response

    4.如果本地已经存在cacheResponse,那么让它和网络得到的networkResponse做比较,决定是否来更新缓存的cacheResponse

    5.缓存未缓存过的response

    缓存拦截器会根据请求的信息和缓存的响应的信息来判断是否存在缓存可用,如果有可以使用的缓存,那么就返回该缓存给用户,否则就继续使用责任链模式来从服务器中获取响应。当获取到响应的时候,又会把响应缓存到磁盘上面

  • ConnectionInterceptor:连接拦截器

    1.判断当前的连接是否可以使用:流是否已经被关闭,并且已经被限制创建新的流;

    2.如果当前的连接无法使用,就从连接池中获取一个连接;

    3.连接池中也没有发现可用的连接,创建一个新的连接,并进行握手,然后将其放到连接池中

  • NetworkInterceptors:网络拦截器(配置OkHttpClient时设置的 NetworkInterceptors)

  • CallServerInterceptor:请求拦截器(负责向服务器发送请求数据、从服务器读取响应数据)

核心

// Call the next interceptor in the chain.
//调用链的下一个拦截器RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request);    //(1)Interceptor interceptor = interceptors.get(index);     //(2)Response response = interceptor.intercept(next);    //(3)
复制代码

1.实例化下一个拦截器对应的RealIterceptorChain对象,这个对象会在传递给当前的拦截器

  1. 得到当前的拦截器:interceptors是存放拦截器的ArryList

  2. 调用当前拦截器的intercept()方法,并将下一个拦截器的RealIterceptorChain对象传递下去

  3. 除了client中用户设置的interceptor,第一个调用的就是retryAndFollowUpInterceptor

小结

1.拦截器用了责任链设计模式,它将请求一层一层向下传,直到有一层能够得到Response就停止向下传递

2.然后将response向上面的拦截器传递,然后各个拦截器会对respone进行一些处理,最后会传到RealCall类中通过execute来得到response

简而言之:每一个拦截器都对应一个 RealInterceptorChain ,然后每一个interceptor 再产生下一个RealInterceptorChain,直到 List 迭代完成,如下图所示

关于调度Dispatch

在开始下面的内容前,我们先简单的对Dispatcher有个认识

Okhttp网络请求工具介绍相关推荐

  1. Fragment标签页+OKHttp网络请求数据+MVP模式

    分包方式 需要的第三方依赖 Fragment 新建两个fragment MainActivity 主页面布局 设置Fragment+tablayout的适配器 Fragment标签页结束 OKHttp ...

  2. Android okHttp网络请求之缓存控制Cache-Control

    前言: 前面的学习基本上已经可以完成开发需求了,但是在项目中有时会遇到对请求做个缓存,当没网络的时候优先加载本地缓存,基于这个需求我们来学习一直okHttp的Cache-Control. okHttp ...

  3. Android 开发之Okhttp网络请求日志打印

    这里写自定义目录标题 Android 开发之Okhttp 网络请求日志打印 OkHTTP网络日志打印 Android 开发之Okhttp 网络请求日志打印 网络请求是开发的日常工作内容之一,网络日志打 ...

  4. Android中使用logger打印完整的okhttp网络请求和响应的所有相关信息(请求行、请求头、请求体、响应行、响应行、响应头、响应体)

    如果你的项目中的网络请求库是Retrofit的话,他的底层封装的是OkHttp,通常调试网络接口时都会将网络请求和响应相关数据通过日志的形式打印出来.OkHttp也提供了一个网络拦截器okhttp-l ...

  5. request 网络请求工具

    /*** request 网络请求工具* @Doc: https://github.com/umijs/umi-request*/ import { clearAuthority } from '@/ ...

  6. java中使用okhttpsoap,Android okHttp网络请求之Retrofit+Okhttp+RxJava组合

    Retrofit介绍: Retrofit和okHttp师出同门,也是Square的开源库,它是一个类型安全的网络请求库,Retrofit简化了网络请求流程,基于OkHtttp做了封装,解耦的更彻底:比 ...

  7. tcp测试监听工具_linux 下两款网络性能测试工具介绍

    前言:最近生产上有点不稳定,开发说网络问题,于是需要测试一下网络环境,出一篇报告验证是否真是网络问题,所以今天正好为大家分享linux下两款网络性能测试工具iperf和netperf 一,iperf安 ...

  8. android okgo 参数map,OkGo 网络请求框架介绍与使用说明

    前言 使用 Android Studio 用户 一般来说,只需要添加第一个 okgo 的核心包即可,其余的三个库根据自己的需要选择添加. //必须使用 compile 'com.lzy.net:okg ...

  9. 微服系列之Feign使用HttpClient和OkHttp网络请求框架

    Feign实现了远程调用,底层默认使用的是HttpURLConnection网络请求框架 那Feign支不支持其他的网络请求框架呢,答案那是肯定的,Feign还支持HttpClient和OkHttp, ...

最新文章

  1. html5 游戏图片预加载,前端实现图片(img)预加载
  2. 关于ospf区域认证以及虚链路之间的配置问题
  3. 没有对“C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files”的写访问权限...
  4. python零基础怎么学-零基础如何入门Python
  5. 125.数据传输方式
  6. 【活体检测】二分类活体检测评价方式
  7. qt定时器暂停与重新开始_手把手教你写个小程序定时器管理库
  8. C++ 作用域与生命周期
  9. iOS:对GCD中 同步、异步、并行、串行的见解
  10. python快速编辑入门答案_1.1、Python快速入门(0529)
  11. cordova app强制横屏
  12. Python程序员职业现状分析,想提高竞争力,就要做到这六点
  13. OTM1287A在MSM8909上的移植
  14. RGB,YUV的来历及其相互转换
  15. 《系统设计》微服务不是银弹
  16. 《动手学机器人学》第四节(上):位姿描述
  17. 基于STC89C52单片机的霓虹灯
  18. Ubuntu18.04系统添加网络打印机以及Windows共享的打印机
  19. 后ERP时代,企业管理软件往哪走?
  20. Android 播放视频时横竖屏的调整

热门文章

  1. 现代化养殖场管理系统_ER图_功能图_数据字典_数据库脚本
  2. 骑行运动耳机哪个好,最值得入手的五款骑行运动耳机推荐
  3. 还在苦恼找素材?实用平面设计素材网站
  4. 一键硬盘安装ghost win10系统
  5. 华盛顿邮报:中国3G之争令西方手机商急上心头
  6. IO虚拟化 - vitio-blk后端驱动分析【转】
  7. h5登录闪退_传奇登录器突然间闪退
  8. “没有名分”的简单工厂模式
  9. win10服务器ip地址修改密码,win10服务器ip地址修改密码
  10. 河北最新道路运输安全员考试真题题库及答案解析