Android OkHttp官方Wiki之Recipes使用方法

本文將演示如何使用OkHttp來解決常見問題,瞭解每件事是如何一起工作的。

Synchronous Get 同步Get

下面的代碼將下載一個txt文件,打印它的響應結果的響應頭部,並將它的響應體作爲字符串打印出來。

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

響應體中的string()方法對於小文檔來時是方便和高效的。但是如果響應體體積很大(大於1Mib),則應避免使用string()方法,因爲它將把整個文檔加載到內存中。在這種情況下,可以將響應體作爲流來處理。

Asynchronous Get異步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 {
        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());
      }
    });
  }

Accessing Headers訪問頭部

典型的HTTP頭部使用Map

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

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

Posting a String /Post發送文檔

本例子使用HTTP POST將請求體發送到服務器,將一個markdown文檔發送到一個將markdown作爲HTML的web服務器上。因爲整個請求體在內存中,所以使用這個API避免發送(大於1個Mib)文檔。

  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 Streaming/Post發送流

在本例中將一個請求體作爲流來進行發送。這個請求體的內容在被寫入時生成。這個示例的請求體數據直接流到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/Post發送文件

使用OkHttp可以很容易將文件作爲請求體來進行發送。

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

    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文件上傳表單兼容的複雜請求體。多部件請求體中的每一個部件本身就是一個請求體,並且可以定義它自己的頭部。如果存在這樣的請求體部件,這些頭部應該描述請求體部件主體,比如它的內容配置Content-Disposition。同時如果這些請求體可用,那麼內容長度Content-Length和內容類型Content-Type將自動添加到頭部字段。

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

Parse a JSON Response With Gson 使用Gson來解析JSON響應

Gson是一個用於在JSON和Java對象之間進行轉換的一個方便的API。在本例中將使用Gson來解碼來自GitHub Api的JSON響應。
注意,下面代碼中的ResponseBody.charStream()方法使用Content-Type響應頭部來選擇在解碼響應體時應使用哪個字符集。如果沒有指定字符集,則默認爲UTF-8。

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

Response Caching 響應緩存

要使OkHttp來緩存響應,用戶需要創建一個可以讀寫的緩存目錄,以及設置緩存大小的限制。該緩存目錄應該是私有的private,不受信任的應用程序不能讀取它的內容。
讓多個緩存同時訪問同一個緩存目錄是錯誤的。大多數應用程序都應該只調用一次new OkHttpClient( ),併爲其配置緩存,並在任何地方使用該OkHttp實例。否則,兩個緩存實例將相互影響,破壞響應緩存,並可能破壞您的程序。
響應緩存使用HTTP頭部來進行所有的配置。用戶可以在請求頭部添加Cache-Control:max-stale=3600的字段,OkHttp的緩存就會執行。用戶的web服務器配置響應緩存的響應頭部來設置響應緩存的大小,例如Cache-Control:max-age=9600。有一些緩存頭部可以強制緩存響應,強制網絡響應,或強制使用有條件的GET對網絡響應進行驗證。

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

當不使用緩存時,可以使用CacheControl.FORCE_NETWORK來防止使用緩存的響應。當只使用緩存,而不使用網絡獲取數據時,可以使用CacheControl.FORCE_CACHE。注意:當使用FORCE_CACHE時,響應結果需要從網絡獲取,OkHttp將返回504 Unsatisfiable Reques 的響應結果。

Canceling a Call 取消一個請求

當發起網絡請求後,可以使用Call.cancel()來停止正在進行的調用。如果一個線程正在寫請求或者讀取響應,將收到一個IOException異常。當一個Call不再需要使用時,可以使用cancel()來保護網絡,例如當用戶退出應用程序時。注意,同步和異步的調用都可以被取消。

  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 響應超時

當網絡請求不可到達時,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();

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

Per-call Configuration 配置Call

所有的HTTP客戶端配置都存在於OkHttpClient中,包括代理設置,超時和緩存。當需要更改單個Call調用的配置時,請調用OkHttpClient.newBuilder()方法,這個方法同樣返回一個OkHttp構建器,該構建器與初始客戶端OkHttpClient.Builder()共享相同的連接池Connection Pool,分發器Dispatcher和配置。在下面的例子中,將使用一個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();

    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處理身份驗證

OkHttp可以自動重試未經身份驗證的請求,例如當響應狀態嗎是401未經授權時,會要求身份驗證者提供證書。用戶應該構建一個新的請求,並附帶缺少的驗證證書。如果沒有可用的證書,則返回null以跳過重試。
使用Response.challenges()方法來獲取任何身份驗證的方案和領域。當需要完成一個基本的身份驗證時,可以使用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 {
            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());
  }

爲了避免在身份驗證無效時進行多次重試,可以返回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;
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章