OkHttp官方使用教程

转载请注明出处:https://blog.csdn.net/mythmayor/article/details/80735224

在这篇文章中,我将告诉你OkHttp常见的使用场景,以及如何解决OkHttp常见的问题,你需要了解这些并明白它们是如何在一起工作的。

同步Get请求(Synchronous Get)

下载一个文件,打印它的响应头,并以字符串形式打印它的响应体。
响应体中的string()方法对于小文档来说非常方便和高效。但是,如果响应体太大(超过1M),请避免使用string(),因为它会将整个文档加载到内存中,在这种情况下,应该使用流方式处理响应体。

private final OkHttpClient client = new OkHttpClient();

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

  try (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());
  }
}

异步Get请求(Asynchronous Get)

在工作线程下载文件,并在响应可读时进行回调,回调会在响应头准备就绪后开始进行。读取响应体时可能会阻塞当前线程。OkHttp目前不提供异步API来部分接收响应体。

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 {
      try (ResponseBody responseBody = response.body()) {
        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(responseBody.string());
      }
    }
  });
}

提取响应头(Accessing Headers)

通常,HTTP标头的工作方式类似于Map<String, String>:每个字段都有一个值或者没有值。但是一些头文件允许多个值,比如Guava的Multimap。例如:HTTP响应提供多个Vary响应头。OkHttp的API让这两种情况都适用。
在写请求头的时候,使用header(name, value)来设置唯一的name、value。如果存在现有值,则在添加新值之前将它们删除。使用addHeader(name, value)来添加一个头,而不必删除已经存在的头。
在读取响应头时,使用header(name)返回最后一次出现的name、value。通常情况这也是唯一的。如果不存在任何值,那么header(name)将会返回null。如果要读取字段所对应的所有值,请使用headers(name),它会返回一个列表。
如果要获取所有的Header,Headers类支持按索引访问。

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
  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();

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

    System.out.println("Server: " + response.header("Server"));
    System.out.println("Date: " + response.header("Date"));
    System.out.println("Vary: " + response.headers("Vary"));
  }
}

Post方式提交String(Posting a String)

使用HTTP POST提交请求到服务。本示例提交了一个Markdown文档到Web服务,并以HTML方式来渲染Markdown。由于整个请求体同时位于内存中,因此请避免使用此API发布较大的文档(大于1MB)。

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();

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

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

Post方式提交流(Post Streaming)

在这里,我们将请求体以流的方式进行提交。请求体的内容由流写入产生。该示例直接流入Okis的BufferedSink。你的程序可能会使用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();

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

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

Post方式提交文件(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();

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

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

Post方式提交表单(Posting form parameters)

使用FormBody.Builder来构建一个像HTML<form>标签相同效果的请求体。键值对将使用与HTML兼容的表单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();

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

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

Post方式提交分块请求(Posting a multipart request)

Multipart.Builder可以构建复杂的请求体,与HTML文件上传形式兼容。多块请求体的每块请求都是一个请求体,并且可以定义它自己的请求头。这些请求头可以用来描述这些请求,例如它的Content-Disposition。如果Content-Length和Content-Type可用的话,它们将自动被添加到请求头中。

/**
 * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running
 * these examples, please request your own client ID! https://api.imgur.com/oauth2
 */
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();

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

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

用Moshi解析Json响应(Parse a JSON Response With Moshi)

Moshi是一个便捷的API,用于在Json和Java对象之间进行转换(Json解析)。这里我们使用它来解析来自GitHub API的Json响应。
请注意,ResponseBody.charStream()使用Content-Type响应头来选择在解析响应体时使用哪个字符集。如果没有指定字符集,它默认为UTF-8。

private final OkHttpClient client = new OkHttpClient();
private final Moshi moshi = new Moshi.Builder().build();
private final JsonAdapter<Gist> gistJsonAdapter = moshi.adapter(Gist.class);

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

    Gist gist = gistJsonAdapter.fromJson(response.body().source());

    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;
}

响应缓存(Response Caching)

要缓存响应,您需要一个可以读取和写入的缓存目录,以及缓存大小的限制。缓存目录应该是私有的,不信任的应用程序不应该能够读取其内容。
多个缓存同时访问相同的缓存目录是错误的。大多数应用程序应该只调用一次new OkHttp(),用它们的缓存对其进行配置,并在任何地方使用同一个实例。否则,两个缓存实例将相互干扰,破坏响应缓存,并可能导致程序崩溃。
响应缓存使用HTTP头作为配置。您可以在请求头中添加Cache-Control: max-stale=3600,OkHttp缓存会支持。你的服务通过响应头确定响应缓存多长时间,例如使用Cache-Control: max-age=9600。有缓存头可强制缓存响应,强制网络响应,或强制网络响应通过条件GET进行验证。

扫描二维码关注公众号,回复: 2408164 查看本文章
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();

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

    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());
  }

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

    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));
}

要防止使用缓存的响应,请使用CacheControl.FORCE_NETWORK。为了防止它使用网络,请使用CacheControl.FORCE_CACHE。警告:如果您使用FORCE_CACHE并且响应需要网络,OkHttp将返回一个504 Unsatisfiable Request响应。

取消一个Call(Canceling a Call)

使用Call.cancel()可以立即停止正在执行的Call。如果一个线程正在写入请求或者读取响应,将会引发IOException。当Call没有必要的时候,使用这个API来节省网络资源。例如当你的用户离开应用程序时,同步或异步的Call都可以取消。
你可以通过tags来同时取消多个请求。当你构建一个请求时,使用Request.Builder().tag(tag)来分配一个标签。之后你就可以用Call.cancel(tag)来取消所有带有这个tag的call。

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);

  System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
  try (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)

当没有响应时使用超时来结束Call。没有响应的原因可能是客户端连接问题、服务器可用性问题等等。OkHttp支持连接、读取和写入超时。

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();

  try (Response response = client.newCall(request).execute()) {
    System.out.println("Response completed: " + response);
  }
}

每个call的配置(Per-call Configuration)

所有的HTTP客户端配置都位于OkHttpClient中,包括代理设置、超时设置和缓存设置。当你需要更改单个Call的配置时,调用OkHttpClient.newBuilder(),它将会返回一个与原始客户端共享相同连接池、调度程序和配置的构建器。在下面的例子中,我们发出一个500毫秒超时的请求,另一个是超时3000毫秒的请求。

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();

  // Copy to customize OkHttp for this request.
  OkHttpClient client1 = client.newBuilder()
      .readTimeout(500, TimeUnit.MILLISECONDS)
      .build();
  try (Response response = client1.newCall(request).execute()) {
    System.out.println("Response 1 succeeded: " + response);
  } catch (IOException e) {
    System.out.println("Response 1 failed: " + e);
  }

  // Copy to customize OkHttp for this request.
  OkHttpClient client2 = client.newBuilder()
      .readTimeout(3000, TimeUnit.MILLISECONDS)
      .build();
  try (Response response = client2.newCall(request).execute()) {
    System.out.println("Response 2 succeeded: " + response);
  } catch (IOException e) {
    System.out.println("Response 2 failed: " + e);
  }
}

处理验证(Handling authentication)

OkHttp可以自动重试未经身份验证的请求。当响应为401未授权(401 Not Authorized)时,认证者(Authenticator)会被要求提供证书。Authenticator的实现中需要建立一个新的包含证书的请求,如果没有证书可用,则返回null来跳过重试。
使用Response.challenges()来获取任何身份验证的方案。当需要实现一个Basic challenge, 使用Credentials.basic(username, password)来编码请求头。

private final OkHttpClient client;

public Authenticate() {
  client = new OkHttpClient.Builder()
      .authenticator(new Authenticator() {
        @Override public Request authenticate(Route route, Response response) throws IOException {
          if (response.request().header("Authorization") != null) {
            return null; // Give up, we've already attempted to authenticate.
          }

          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();

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

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

为避免在身份验证不起作用时进行多次重试,可以返回null来放弃。例如,您可能想要在尝试完成这些确切证书时跳过重试:

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;
}

猜你喜欢

转载自blog.csdn.net/mythmayor/article/details/80735224