OkHttp 4.0 Kotlin源码分析 (一) 同步和异步请求基本用法

前言

HTTP是一种比较流行的用于数据和多媒体流数据的交换的网络协议。高效的使用HTTP可以使你的应用加载更快并节省带宽。

OKhttp就是一个可以高效使用HTTP的客户端, Okhttp包含一下四大特性:
  1. 支持 HTTP/2 允许对同一主机的所有请求共享Socket
  2. 使用连接池,减少了请求的延迟
  3. 支持GZIP 减小了传输的大小
  4. 支持响应缓冲,完全避免了重复请求的情况出现

更多介绍内容参见官网:
https://square.github.io/okhttp/

其他相关文章

OkHttp 4.0 Kotlin源码分析 (一) 同步和异步请求基本用法

OkHttp 4.0 Kotlin源码分析 (二) 基本的数据对象以及Call类分析

OkHttp 4.0 Kotlin源码分析 (三) Dispatcher分发器流程控制

1. OKhttp3 的基本用法

1.1 版本说明

Okhttp 3.12.x supports Android 2.3+ (API level 9+) and Java 7+ , 在2020.12.31之前将对3.12.x版本提供关键性修复。
OkHttp 3.13.x supports Android 5.0+ (API level 21+) and Java 8+.

1.2 库的下载

在gradle文件中加入一下代码:

  implementation("com.squareup.okhttp3:okhttp:3.13.1")

1.3 Okhttp的使用范例

范例 (一)

这是同步Get请求,程序完成的任务是获取一个URL,并将获取到的内容转换为String进行打印。

package okhttp3.guide;

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetExample {
  //1. 创建OkhttpClient 对象
  OkHttpClient client = new OkHttpClient();

  String run(String url) throws IOException {
    //2. 创建请求的Request 对象
    Request request = new Request.Builder()
        .url(url)
        .build();

    //3. 在Okhttp中创建Call 对象,将request和Client进行绑定
    //4. 执行Call对象(call 是interface 实际执行的是RealCall)中的`execute`方法
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  public static void main(String[] args) throws IOException {
    GetExample example = new GetExample();
    String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
    System.out.println(response);
  }
}
范例 (二)

这是一个android 程序,完成了一次异步的POST请求,将数据Post到服务器.

    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final String TAG = "OkHttp3";

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

        String json = bowlingJson("Jesse", "Jake");
        String url = "http://www.roundsapp.com/post";

        //1. 创建OkhttpClient 对象
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        //2. 创建请求的Request 对象
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        //3. 在Okhttp中创建Call 对象,将request和Client进行绑定
        Call call = client.newCall(request);
        //4. 执行Call对象(call 是interface 实际执行的是RealCall)中的 `enqueue`方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, e.toString());
            }

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

    }

    String bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
    }
}

1.4 总结

以上是Okhttp的基本使用方法,列举了两个范例分别是,

  • GET请求的同步调用
  • POST请求的异步调用

对比范例中的代码注释,不管是同步还是异步请求都有四个关键的步骤:

    1. 创建OkhttpClient 对象
    1. 创建请求的Request 对象
    1. 在Okhttp中创建Call 对象,将request和Client进行绑定
    1. 执行Call对象(call 是interface 实际执行的是RealCall)中的execute()enqueue()方法

我们发现,同步和异步请求唯一区别是,最后调用的Call对象的方法不同, 同步调用是execute()方法,而异步调用的是enqueue()

疑问?

1.OkhttpClient和Request对象是什么作用,又是怎么进行绑定的呢?
2.Call对象的这两方法有什么不同呢,又是怎么进行同、异步处理的?


下篇我们讲解 Okhttp基本的数据对象以及Call类分析

你可能感兴趣的:(OkHttp 4.0 Kotlin源码分析 (一) 同步和异步请求基本用法)