okhttp基本概念

okhttp基本概念

okhttp官网

An HTTP client for Android, Kotlin, and Java.

官方介绍:Android, Kotlin, JavaHTTP客户端

基本类

在使用okhttp时,我们一定会碰到的一些类的介绍

基本的网络请求

下面是使用okhttp一串最基本的网络请求

OkHttpClient httpClient = new OkHttpClient.Builder()
        .build();

Request request = new Request.Builder()
        .url("https://wanandroid.com/wxarticle/chapters/json")
        .get()
        .build();

Call call = httpClient.newCall(request);
Response response = call.execute();

System.out.println(response.body().string());

1. Request

An HTTP request. Instances of this class are immutable if their {@link #body} is null or itself immutable.

翻译:代表有一个HTTP请求,这个类的实例是不可变的。

Request有多个属性:urlmethodheaderbodytag

字面意思很简单,需要解释一下的是tag,标记这个request,在interceptorevent listenercallback中都可以特殊处理标记的request

body实际上是RequestBody对象,通常当请求methodPOSTPUT之类的时可以使用。

2. RequestBody

HTTP的请求体,如POST提交表单。

常用到的有两个子类:FormBodyMultipartBody。前者多用于POST表单提交,后者多用于文件上传。

3. Call

A call is a request that has been prepared for execution. A call can be canceled. As this object represents a single request/response pair (stream), it cannot be executed twice.

翻译:Call表示将Request请求为执行做准备。Call可以被取消。它只代表单独的一个请求-相应对,所以不能被执行两次。

Call是一个接口,包含的主要方法:Response execute()void enqueue(Callback)cancel(),分别表示同步执行、加入队列等待执行、取消执行。

4. Response

An HTTP response. Instances of this class are not immutable: the response body is a one-shot value that may be consumed only once and then closed. All other properties are immutable.

翻译:HTTP响应。实例不可变:其中的ResponseBody是一次性的值,当被消费一次之后就会被关闭。其他所有属性都是不可变的。

Response封装了响应结果,其中主要的属性有:codemessagerequestheaderbody

body指的是ResponseBody

5. ResponseBody

A one-shot stream from the origin server to the client application with the raw bytes of the response body. Each response body is supported by an active connection to the webserver. This imposes both obligations and limits on the client application.

翻译:远程服务器响应客户端请求得到的一次性的二进制数据流。每个ResponseBody依赖于活跃的与服务器的连接。这种机制强行限制了客户端应用的使用。

ResponseBody实际上将返回的数据作为流来处理,最重要方法是BufferedSource source(),得到BufferedSource流接口,可以转换成真实数据。

责任链 Chain of Responsibility

The chain of responsibility pattern let these object which can handle the request of customer become to a chain,and a handler of the responsibility chain handles the request of a customer or deliver the request of a customer to next handler of the chain of responsibility.

责任链模式将处理用户请求的对象形成一个链,责任链上的每个处理者要么处理用户的请求,要么把请求传递给责任链上的下一个处理者


   转载规则


《okhttp基本概念》 Mycroft Wong 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
okhttp请求与响应执行过程 okhttp请求与响应执行过程
okhttp请求与响应执行过程前言不考虑真正的网络请求部分,看一下从一个Request到Response的过程。 请求再来看一下上一篇最简单的执行代码 OkHttpClient httpClient = new OkHttpClient.B
下一篇 
okhttp系列 okhttp系列
OkHttp架构分析
OkHttp是一个非常好用的网络数据库,本系列文章以OkHttp 3.14.2版本,也是最后一个Java版本
  目录