1. 程式人生 > >深入理解OkHttp3:(四)常用事例Demo

深入理解OkHttp3:(四)常用事例Demo

這裡彙總編寫了一些演示如何使用OkHttp解決常見問題的方法。通讀它們,瞭解它們是如何協同工作的。可以在需要的時候,隨意剪下貼上這些示例;

1.同步GET(Synchronous GET)

下載一個檔案,列印它的標題,並列印它的響應主體作為字串。

響應體(Body)上的string()方法對於小文件來說既方便又高效。但是,如果響應主體很大(大於1 MiB),請避免string(),因為它將把整個文件載入到記憶體中。在這種情況下,更喜歡把身體當作一個流來處理。

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

public final class SynchronousGet {
  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());
    }
  }

  public static void main(String... args) throws Exception {
    new SynchronousGet().run();
  }
}

2.非同步GET(Asynchronous GET)

在工作執行緒上下載檔案,並在響應可讀時被呼叫。回撥是在響應Header就緒後進行的。讀取響應體仍然可能阻塞。OkHttp目前不提供非同步api分段來接收響應體。

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public final class AsynchronousGet {
  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());
        }
      }
    });
  }

  public static void main(String... args) throws Exception {
    new AsynchronousGet().run();
  }
}

3.訪問Headers(Accessing Headers)

通常HTTP報頭的工作方式類似於Map<String, String>:每個欄位都有一個值或沒有。但有些標頭允許多個值,比如Guava的Multimap。例如,HTTP響應提供多個不同的Headers是合法和常見的。OkHttp的api試圖讓所有情況都變得簡單易處理。

在編寫請求Headers時,使用Headers(名稱、值)方法將唯一出現的名稱設定為值。如果存在現有值,則在新增新值之前將刪除它們。使用addHeader(名稱、值)方法新增標題,而不刪除已經出現的標題。

在讀取響應Headers時,使用header(name)方法返回最後一次出現的value。通常這也是唯一可能發生的情況!如果不存在值,header(name)方法將返回null。要將欄位的所有值作為列表讀取,請使用headers(name)方法。

要訪問所有Header,請使用支援按索引訪問的Headers類。

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

public final class AccessHeaders {
  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"));
    }
  }

  public static void main(String... args) throws Exception {
    new AccessHeaders().run();
  }
}

4.用POST傳送一個字串(Posting a String)

使用HTTP POST向服務端傳送請求體。這個示例將標記文件傳送給使用HTML呈現的web服務端。同時因為整個請求主體在記憶體中,所以避免使用此API傳送較大(大於1 MiB)的文件。

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

public final class PostString {
  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.get("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());
    }
  }

  public static void main(String... args) throws Exception {
    new PostString().run();
  }
}

5.傳送流(Post Streaming)

在這裡,我們將請求主體作為流傳送給服務端。這個請求主體的內容在編寫時生成。這個示例直接流到Okio緩衝接收器中。您的程式可能更喜歡OutputStream,您可以從BufferedSink.outputStream()中獲得它。

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

public final class PostStreaming {
  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.get("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());
    }
  }

  public static void main(String... args) throws Exception {
    new PostStreaming().run();
  }
}

6.用Post方法傳送一個檔案(Posting a file)

用一個檔案來作為請求body,是一件很簡單的事情。

import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public final class PostFile {
  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.get("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());
    }
  }

  public static void main(String... args) throws Exception {
    new PostFile().run();
  }
}

7.用post傳送表單資料到服務埠(Posting form parameters)

使用FormBody.Builder構建器來構建一個類似於HTML <form>標記的請求體。名稱和值將使用html相容的表單URL編碼進行編碼。

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

public final class PostForm {
  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());
    }
  }

  public static void main(String... args) throws Exception {
    new PostForm().run();
  }
}

8.釋出MultipartBody請求(Posting a multipartBody request)

MultipartBody.Builder構造器可以構建與HTML檔案上傳表單相容的複雜請求體。多部分請求體的每個部分本身就是請求體,可以定義自己的頭。如果存在,這些header應該描述對應部分主體,例如其內容配置。如果內容長度和內容型別header可用,則會自動新增它們。

import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public final class PostMultipart {
  /**
   * 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 = "9199fdef135c122";
  private static final MediaType MEDIA_TYPE_PNG = MediaType.get("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());
    }
  }

  public static void main(String... args) throws Exception {
    new PostMultipart().run();
  }
}

9.用Moshi解析JSON響應

Moshi是一個方便的API,用於在JSON和Java物件之間進行轉換。這裡,我們使用它從GitHub API解碼JSON響應。

注意,ResponseBody.charStream()使用Content-Type響應頭來確定解碼響應主體時使用的字符集。如果沒有指定字符集,則預設為UTF-8。

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public final class ParseResponseWithMoshi {
  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;
  }

  public static void main(String... args) throws Exception {
    new ParseResponseWithMoshi().run();
  }
}

10.Responses快取

要快取響應,您需要一個可以讀寫的快取目錄,以及對快取大小的限制。快取目錄應該是私有的,不受信任的應用程式不應該能夠讀取它的內容!

讓多個快取同時訪問同一個快取目錄是錯誤的。大多數應用程式應該只調用一次新的OkHttpClient(),使用它們的快取配置它,並在任何地方使用相同的例項。否則,這兩個快取例項將相互參雜在一起,破壞響應快取,並可能導致程式崩潰。

響應快取對所有配置使用HTTP Header。你可以新增像cache-control: max-stale=3600這樣的請求header,OkHttp的快取將會支援它們。您的服務端通過它自己的響應header來配置快取響應的時間,比如Cache-Control: max-age=9600。快取header用於強制快取響應、強制網路響應或強制使用條件GET驗證網路響應。

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

public final class CacheResponse {
  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));
  }

  public static void main(String... args) throws Exception {
    new CacheResponse(new File("CacheResponse.tmp")).run();
  }
}

要防止響應使用快取,請使用CacheControl.FORCE_NETWORK。為了防止它使用網路,使用CacheControl.FORCE_CACHE。注意:如果您使用FORCE_CACHE,並且響應需要網路,那麼OkHttp將返回一個504不可滿足的請求響應。

11.取消一個呼叫(Call)

使用call.cancel()方法立即停止正在進行的呼叫。如果執行緒當前正在編寫請求或讀取響應,它將收到IOException。當不再需要呼叫時,使用此方法節省網路資源;例如,當用戶從應用程式導航離開時。同步和非同步呼叫都可以取消。

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CancelCall {
  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);
    }
  }

  public static void main(String... args) throws Exception {
    new CancelCall().run();
  }
}

12.超時(Timeouts)

當呼叫的對等端不可到達時,使用timeouts來結束一次呼叫。網路分割槽可能是由於客戶端連線問題、伺服器可用性問題或兩者之間的任何問題。OkHttp支援連線、讀和寫超時。

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public final class ConfigureTimeouts {
  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);
    }
  }

  public static void main(String... args) throws Exception {
    new ConfigureTimeouts().run();
  }
}

13.更改單個Call的配置

所有HTTP客戶端配置都存在於OkHttpClient中,包括代理設定、超時和快取。當您需要更改單個Call的配置時,請呼叫OkHttpClient.newBuilder()。這將返回一個構建器,該構建器與原始客戶端共享相同的連線池、排程程式和配置。在下面的示例中,我們提出一個請求,超時時間為500毫秒,另一個請求超時時間為3000毫秒。

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public final class PerCallSettings {
  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);
    }
  }

  public static void main(String... args) throws Exception {
    new PerCallSettings().run();
  }
}

14.處理身份驗證

OkHttp可以自動重試未經身份驗證的請求。如果沒有授權的401響應,則要求Authenticator提供證書。具體實現應該構建一個包含丟失證書的新請求。如果沒有證書可用,返回null以跳過重試。

使用Response.challenges()獲得任何身份驗證質詢的方案和領域。當完成一個基本的身份驗證質詢時,使用Credentials.basic(username, password)方法編碼請求Header。

import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;

public final class Authenticate {
  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());
    }
  }

  public static void main(String... args) throws Exception {
    new Authenticate().run();
  }
}

為了避免在身份驗證不起作用時進行多次重試,您可以返回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.
  }

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