图解OkHttp -- (1) OkHttp使用入门

前言

  • 本文涉及源码均基于okhttp 3.14.9

一、OkHttp简介

  • OkHttp是Android开发最常用的网络请求框架,由Square公司开源。
  • Android4.4以后,源码中HttpURLConnection底层实现已经替换成了OKHttp
  • 目前流行的Retrofit框架底层也是基于OKHttp实现。
  • OkHttp4.x已经改为kotlin实现。

二、OkHttp优点

  • 支持Http1Http2QuicWebSocket协议。
  • 连接池复用底层TCP(Socket),减少请求延时。
  • 支持GZIP,减少数据流量。
  • 缓存响应数据减少重复的网络请求 。
  • 请求失败支持自动重试其他IP。
  • 支持自动重定向

三、基本配置

依赖导入

项目导入依赖

    implementation 'com.squareup.okhttp3:okhttp:3.14.9'
权限配置

使用时,需要在清单文件AndroidManifest.xml中配置网络使用权限

<uses-permission android:name="android.permission.INTERNET" />

四、OkHttp使用流程

okttp使用流程.png

由上图可知,使用OkHttp发起一个请求的具体步骤如下:

  • 1 通过OkHttpClient.Builder创建OkHttpClient
  • 2 通过Request.Builder创建Request
  • 3 调用OkHttpClient对象的newCall方法,传入Request,生成Call
  • 4 由Call对象调用execute或者enqueue方法得到响应Response

五、Get 方式发起请求

同步请求
        String url="xxx";
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        try {
    
    
            Response response = call.execute();
            Log.d(TAG, response.body().string());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
异步请求
        String url="xxx";
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
    
    
            @Override
            public void onFailure(Call call, IOException e) {
    
    
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
    
    
                Log.d(TAG, response.body().string());
            }
        });

六、归纳小结

由上述流程和例子可知:

  • 使用OkHttp发起一次请求时,核心是OkHttpClientRequestCall三个角色。
  • 其中OkHttpClientRequest的创建使用均由对应的Builder实现(经典的建造者设计模式)。
  • 使用Call对象的execute方法发起的是同步请求,而enqueue方法则是异步请求

猜你喜欢

转载自blog.csdn.net/qq_22255311/article/details/125375179