OKHTTP 的使用完全解析

一、前言

        在Android客户端开发中,使用网络请求是非常常见的事情,一般我们使用HttpURLConnection是可以满足需求的,不过随着业务逻辑复杂,依然还是有很多不便,一个神奇的公司square开源了一个网络请求库——Okhttp。随着Okhttp越来越火,越来越多的人使用Okhttp+retrofit+Rxjava,我们还是很有必要了解一下。本文的实力代码来自官方wiki。

二、下载配置

        现在最新的版本是3.X,android支持2.3+,java应用程序中使用,java最低版本是1.7。
        可以通过下载jar包获取,也可以通过Maven获取:

<dependency>
  <groupId>com.squareup.okhttp3groupId>
  <artifactId>okhttpartifactId>
  <version>3.4.1version>
dependency>

        或者Gradle

compile 'com.squareup.okhttp3:okhttp:3.4.1'

三、基础使用

  • Synchronous (同步的) Get
private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Headers responseHeaders = response.headers();
    for (int i = 0; i < responseHeaders.size(); i++) {
      System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
    }

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

        OkHttpClient 创建一个请求对象,我们可以通过这个配置缓存、超时目录、代理、拦截器等,大多数时候我们只应该创建一个对象,所有的请求可以共用缓存、连接池、 `拦截器等,如下所示:

OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(8000, TimeUnit.SECONDS)
            .connectTimeout(8000, TimeUnit.SECONDS)
            .writeTimeout(8000, TimeUnit.SECONDS)
            .addInterceptor(new Interceptor())
            .cache(cache)
            .build();

        Requests 请求,每个HTTP请求包含一个URL、一个方法(如GET或POST),同时包含头信息的列表。请求也可能包含一个实体:具体类型内容的数据流。

        Responses 响应,根据请求返回的响应码(成功的200或没有找到内容的404),头信息,和可选的实体。

        Calls 代表一个实际的http请求,一般调用会执行两种方式中的一种:

        - 同步:执行execute()方法,你的线程被锁住直到响应返回.
        - 异步:执行enqueue()方法,你在任何线程安排请求,在另一个线程获得响应回调,不会阻塞当前线程,通过Callback 对象的成功和失败方法获取响应。

OKHTTP 的使用完全解析_第1张图片

        以上代码运行返回如图所示,上面几行是响应头信息,我们可以通过Resbonse的response.headers() 的到Headers对象,我们可以通过索引遍历获取响应头的信息和值,我们不通过遍历也可以通过responseHeaders.get("Cache-Control"); 获取,如果响应头一样,有多个值返回,我们可以通过`public List values(String name) {} 返回一个集合,如果通过Header对象的get方法获取只会返回最后一个数据。

        下面返回的就是获得响应体对象response.body() ,调用string() 方法将其转成string对象,对小文件来说string()方法响应实体是方便和高效的.但如果响应实体很大(大于1 MiB),避免使用string(),因为它会将整个文档加载到内存中.在这种情况下,更倾向于用流处理实体。 `

  • Asynchronous(异步) Get
    代码如下所示:
 private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Headers responseHeaders = response.headers();
        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
          System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
        }

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

        以上代码异步执行,不会阻塞当前线程,该方法接受一个okhttp3.callback对象,当请求成功后执行callback对象的onResponse方法,我们通过调用isSuccessful() 可以判断返回的响应码是否在200和300之间。当请求失败或取消的会调用callback对象的onFailure 。回调的方法都是执行在工作线程的,不可以直接更新UI。

  • Accessing Headers 访问头信息
            典型的HTTP头信息的工作像一个Map每个字段都有一个值或没有。但是一些头信息允许多个值,如 Guava’s Multimap.例如,一个HTTP响应提供多个不同的头信息是合法和常见的。OkHttp’s APIs试图使这两种情况下都方便使用,当写请求头信息时,使用header(name, value)为value设置唯一的name。如果values已经存在,他们将被删除然后添加的新value。使用addHeader(name, value)来添加一个新的头信息而不需要移除已经存在的头信息。如下所示:
  Request request = new Request.Builder()
        .url("https://api.github.com/repos/square/okhttp/issues")
        .header("User-Agent", "OkHttp Headers.java")
        .addHeader("Accept", "application/json; q=0.5")
        .addHeader("Accept", "application/vnd.github.v3+json")
        .build();
  • Posting a String 上传字符串
    代码如下所示
public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    String postBody = ""
        + "Releases\n"
        + "--------\n"
        + "\n"
        + " * _1.0_ May 6, 2013\n"
        + " * _1.1_ June 15, 2013\n"
        + " * _1.2_ August 11, 2013\n";

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

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

        post方发接收一个RequestBody 对象,使用一个HTTP POST发送请求实体到服务.这个例子提交一个markdown文档发送给web服务,将markdown呈现为HTML.因为整个请求实体同时在内存中,避免使用这个API发布大文档(大于1 MiB).

  • Post 提交键值对
    其实提交键值对跟上传表格参数差不多,我们一般都是一个Map集合传递近来就是了,不用每次都要一个一个add,如下所示:
private final OkHttpClient client = new OkHttpClient();
    public void run(Map<String, String> params) throws Exception{
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()){
            builder.add(entry.getKey(),entry.getValue().toString());
        }
        RequestBody formBody = builder.build();
        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
    }
  • Post 提交json
public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}
  • Post Streaming 上传流
    这里我们发布一个请求实体作为一个流. 这个请求实体被写的时候它的内容就产生了.这个例子的流直接进入到 Okio 缓冲池.你的项目可能更喜欢一个OutputStream,你可以从BufferedSink.outputStream()获取.
 public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
      @Override public MediaType contentType() {
        return MEDIA_TYPE_MARKDOWN;
      }

      @Override public void writeTo(BufferedSink sink) throws IOException {
        sink.writeUtf8("Numbers\n");
        sink.writeUtf8("-------\n");
        for (int i = 2; i <= 997; i++) {
          sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
        }
      }

      private String factor(int n) {
        for (int i = 2; i < n; i++) {
          int x = n / i;
          if (x * i == n) return factor(x) + " × " + i;
        }
        return Integer.toString(n);
      }
    };

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(requestBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
  • Posting a File 上传文件
    很容易使用一个文件作为请求实体.
 public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    File file = new File("README.md");

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
  • Posting form parameters 上传表格参数
    使用FormBody.Builder构建的请求实体,工作起来就像一个HTML 标签。名称和值将使用一种 HTML-compatible 的URL编码。
private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    RequestBody formBody = new FormBody.Builder()
        .add("search", "Jurassic Park")
        .build();
    Request request = new Request.Builder()
        .url("https://en.wikipedia.org/w/index.php")
        .post(formBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
  • Posting a multipart request 上传多部分的请求
    MultipartBody.Builder 可以构建兼容HTML文件上传表单的复杂的请求实体。一个多部分请求的每个部分本身就是一个请求实体,并可以定义自己的头信息。如果存在的话,这些头信息应该描述该部分实体,比如它的内容目录.内容长度和内容类型的头信息如果可用的话会自动添加。
private static final String IMGUR_CLIENT_ID = "...";
  private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "Square Logo")
        .addFormDataPart("image", "logo-square.png",
            RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
        .build();

    Request request = new Request.Builder()
        .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
        .url("https://api.imgur.com/3/image")
        .post(requestBody)
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

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

        设置setType 我们一般将该值设置为MultipartBody.FORMaddFormDataPart(String name, String value) 我们可以向里面添加键值对,addFormDataPart(String name, String filename, RequestBody body) 我们可以向里面添加文件,addPart 提供了三个重载方法,我们可以通过addPart(Headers headers, RequestBody body)可以在添加RequestBody的时候,同时为其单独设置请求头。如下所示:

RequestBody requestBody = new MultipartBuilder()
     .type(MultipartBuilder.FORM)
     .addPart(Headers.of("Content-Disposition", 
              "form-data; name=\"username\""), 
          RequestBody.create(null, "test"))
     .build();
  • Parse a JSON Response With Gson 用Gson解析一个JSON响应
    Gson 是一个方便JSON和Java对象之间互相转换的API.这里我们用它来解析一个来自GitHub API的JSON响应.
 private final OkHttpClient client = new OkHttpClient();
  private final Gson gson = new Gson();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("https://api.github.com/gists/c2a7c39532239ff261be")
        .build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
    for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
      System.out.println(entry.getKey());
      System.out.println(entry.getValue().content);
    }
  }

  static class Gist {
    Map<String, GistFile> files;
  }

  static class GistFile {
    String content;
  }

        上面就是通过Gson解析返回的数据,跟平时用法差不多。

  • Response Caching 响应缓存
    缓存平时我们用的还是挺多的,下面示例代码演示:
private final OkHttpClient client;

  public CacheResponse(File cacheDirectory) throws Exception {
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(cacheDirectory, cacheSize);

    client = new OkHttpClient.Builder()
        .cache(cache)
        .build();
  }

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    Response response1 = client.newCall(request).execute();
    if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);

    String response1Body = response1.body().string();
    System.out.println("Response 1 response:          " + response1);
    System.out.println("Response 1 cache response:    " + response1.cacheResponse());
    System.out.println("Response 1 network response:  " + response1.networkResponse());

    Response response2 = client.newCall(request).execute();
    if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);

    String response2Body = response2.body().string();
    System.out.println("Response 2 response:          " + response2);
    System.out.println("Response 2 cache response:    " + response2.cacheResponse());
    System.out.println("Response 2 network response:  " + response2.networkResponse());

    System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
  }

        为了缓存响应,你需要一个缓存目录,你可以读和写,并限制缓存的大小。缓存目录应该是私有的,不受信任的应用程序不应该能够阅读其内容,所以我们一般这样配置,缓存的数据存放在context.getCacheDir()的子目录中::

final @Nullable File baseDir = context.getCacheDir();
if (baseDir != null) {
  final File cacheDir = new File(baseDir, "HttpResponseCache");
  okHttpClient.setCache(new Cache(cacheDir, 10 * 10 * 1024));
}

        第一次请求完成后,Okhttp将请求结果写入了缓存当中,第一次response1.networkResponse()为请求的值,response1.cacheResponse() 打印的值为null;第二次response2.cacheResponse() 打印的是第一次网络请求的值,response2.networkResponse() 打印的值是null,说明你第一次走的网络请求,第二次请求来自于缓存,两次的值response1Body.equals(response2Body) 返回也是true,很好的验证上面的说法。我们还可以配置响应头信息Cache-Control:max-stale=3600 Cache-Control: max-age=9600 ,okhttp也会对配置进行缓存处理,超过时间走网络请求。禁止一个响应使用缓存,只获取网络响应,使用CacheControl.FORCE_NETWORK。禁止一个响应使用网络,只使用缓存,使用CacheControl.FORCE_CACHE。注意:如果你使用FORCE_CACHE请求缓存,缓存不存在,,OkHttp将返回一个504不可满足的请求响应。

  • Canceling a Call 取消一个调用
    当一个activity退出的时候,使用 Call.cancel()立即停止一个正在进行中的调用,如果一个线程正在写一个请求或读一个响应,它将接收一个 IOException。下面请求服务端会有两秒延迟,客户端发出请求1秒的时候,请求还未完成,这个时候终止了请求,抛出了IOException
 private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
        .build();

    final long startNanos = System.nanoTime();
    final Call call = client.newCall(request);

    // Schedule a job to cancel the call in 1 second.
    executor.schedule(new Runnable() {
      @Override public void run() {
        System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
        call.cancel();
        System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
      }
    }, 1, TimeUnit.SECONDS);

    try {
      System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
      Response response = call.execute();
      System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
          (System.nanoTime() - startNanos) / 1e9f, response);
    } catch (IOException e) {
      System.out.printf("%.2f Call failed as expected: %s%n",
          (System.nanoTime() - startNanos) / 1e9f, e);
    }
  }
  • Timeouts 超时
    访问服务器一般分为3部分,客服端和服务端建立连接connectTimeout,客户端发送数据到服务端writeTimeout,服务端将相应数据发送到客户端readTimeout,这三步每一步都有可能耗时,所以我们设置耗时时间非常有必要,超过某一部分时间就要抛出异常。
  private final OkHttpClient client;

  public ConfigureTimeouts() throws Exception {
    client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();
  }

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
        .build();

    Response response = client.newCall(request).execute();
    System.out.println("Response completed: " + response);
  }
  • Per-call Configuration 每个调用的设置
    所有的HTTP客户端配置在OkHttpClient中,包括代理设置,超时和缓存。当你需要为单个调用改变配置的时候,调用OkHttpClient.newBuilder(),这返回一个builder,分享同样的连接池,分配器和原始OkHttpClient的配置。在下面的示例中,我们让一个请求500ms 超时,另一个请求3000 ms超时。
 private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
        .build();

    try {
      // Copy to customize OkHttp for this request.
      OkHttpClient copy = client.newBuilder()
          .readTimeout(500, TimeUnit.MILLISECONDS)
          .build();

      Response response = copy.newCall(request).execute();
      System.out.println("Response 1 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 1 failed: " + e);
    }

    try {
      // Copy to customize OkHttp for this request.
      OkHttpClient copy = client.newBuilder()
          .readTimeout(3000, TimeUnit.MILLISECONDS)
          .build();

      Response response = copy.newCall(request).execute();
      System.out.println("Response 2 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 2 failed: " + e);
    }
  }
  • Handling authentication 处理身份验证
 private final OkHttpClient client;

  public Authenticate() {
    client = new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
          @Override public Request authenticate(Route route, Response response) throws IOException {
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
          }
        })
        .build();
  }

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/secrets/hellosecret.txt")
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

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

        OkHttp可以自动重试未经身份验证的请求,当响应401未授权, 一个Authenticator被访问来提供证书,如果返回的响应码是code=401, message=Unauthorized ,则会调用OkHttpClient.Builder()authenticator 方法,对新的request对象调用header("Authorization", credential) ;如果返回的是407 proxy unauthorized ,则是不是服务器最终要求的客户端的登陆信息,就要调用OkHttpClient.Builder()proxyAuthenticator()方法,调用和上面一样,对新的request对象添加头部信息。如果用户名或者密码有问题,那么okhttp会一直使用这个错误的信息尝试,那么我们应该加一个判断,如果之前用该用户名和密码登陆失败了,就不应该再次登录:

 if (credential.equals(response.request().header("Authorization"))) {
    return null; // If we already failed with these credentials, don't retry.
   }

        当你设置一个应用程序定义的限制时你也可以跳过重试:

  if (responseCount(response) >= 3) {
    return null; // If we've failed 3 times, give up.
  }

        这上面的代码依赖于 responseCount() 方法:

 private int responseCount(Response response) {
    int result = 1;
    while ((response = response.priorResponse()) != null) {
      result++;
    }
    return result;
  }

四、总结

        Okhttp很强大,我们看一下wiki基本上就可以上手,下一篇我会讲解拦截器和其他配置。

你可能感兴趣的:(Android开发)