OkHttp之示例

我們寫(xiě)了一些方法來(lái)示例如果使用OkHttp來(lái)解決常見(jiàn)問(wèn)題。通讀它們了解它們是如何一起工作的。隨意地進(jìn)行復(fù)制、粘貼,這是它們存在的目的。

同步Get請(qǐng)求

下載一個(gè)文件,打印它的頭,并將其響應(yīng)主體以字符串形式打印。

作用在響應(yīng)主體上的string()方法對(duì)于小文檔來(lái)說(shuō)是方便和高效的。但是如果響應(yīng)主體比較大(大于1MB),避免使用string(),因?yàn)樗鼤?huì)加載整個(gè)文檔到內(nèi)存中。在這種情況下,優(yōu)先使用stream來(lái)處理主體。

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

異步Get請(qǐng)求

在一個(gè)工作線程下載一個(gè)文件,當(dāng)響應(yīng)可讀時(shí)獲取回調(diào)。這個(gè)回調(diào)將在響應(yīng)頭準(zhǔn)備好時(shí)執(zhí)行。讀取響應(yīng)主體可能仍然阻塞。OkHttp當(dāng)前沒(méi)有提供異步API來(lái)局部地接收響應(yīng)主體。

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

訪問(wèn)Header

典型的HTTP頭工作起來(lái)像一個(gè)Map< String, String >,每一個(gè)字段有一個(gè)值或沒(méi)有值。但是有一些頭允許多個(gè)值,像Guava的Multimap。對(duì)于一個(gè)HTTP響應(yīng)來(lái)應(yīng)用多個(gè)Vary頭是合法的并且常見(jiàn)的。OkHttp的API試圖兼容這些情況。

當(dāng)寫(xiě)請(qǐng)求頭時(shí),使用header(name, value)的方式來(lái)設(shè)置唯一出現(xiàn)的鍵值。如果已有值,會(huì)在新值添加前移除已有值。使用addHeader(name, value)來(lái)添加一個(gè)頭而不移除已經(jīng)存在的頭。

當(dāng)讀取一個(gè)響應(yīng)頭時(shí),使用header(name)來(lái)返回最后一次出現(xiàn)的鍵值對(duì)。通常這是唯一出現(xiàn)的鍵值對(duì)。如果不存在值,header(name)會(huì)返回null。使用headers(name)來(lái)用一個(gè)list讀取一個(gè)字段的所有值。

使用支持按索引訪問(wèn)的Headers類來(lái)訪問(wèn)所有的頭。

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

上傳字符串

使用HTTP POST來(lái)發(fā)送請(qǐng)求主體到服務(wù)器。這個(gè)例子上傳了一個(gè)markdown文檔到一個(gè)用HTML渲染markdown的服務(wù)器中。因?yàn)檎麄€(gè)請(qǐng)求主體同時(shí)存在內(nèi)存中,避免使用這個(gè)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();

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

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

上傳流

這里以stream的形式上傳請(qǐng)求主體。請(qǐng)求主體的內(nèi)容如它寫(xiě)入的進(jìn)行生成。這個(gè)示例stream直接放入到了Okio緩存sink中。你的程序可能需要一個(gè)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());
  }

上傳文件

使用文件作為請(qǐng)求主體很容易。

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

上傳表格參數(shù)

使用FormBody.Builder來(lái)構(gòu)建一個(gè)工作起來(lái)像HTML< form >標(biāo)簽的請(qǐng)求主體。鍵值對(duì)會(huì)使用一個(gè)兼容HTML form的URL編碼進(jìn)行編碼。

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

上傳多部分請(qǐng)求

MultipartBody.Builder可以構(gòu)造復(fù)雜的請(qǐng)求主體與HTML文件上傳表單兼容。multipart請(qǐng)求主體的每部分本身就是一個(gè)請(qǐng)求主體,可以定義它自己的頭。如果存在自己的頭,那么這些頭應(yīng)該描述部分主體,例如它的Content-Disposition。Content-Length和Content-Type會(huì)在其可用時(shí)自動(dòng)添加。

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

使用Gson解析Json響應(yīng)

Gson是一個(gè)便利API來(lái)實(shí)現(xiàn)JSON和Java對(duì)象之間的轉(zhuǎn)化。這里我們使用它來(lái)解碼來(lái)自GitHub API的JSON響應(yīng)。

ResponseBody.charStream()使用響應(yīng)頭Content-Type來(lái)確定在解碼響應(yīng)主體時(shí)使用哪個(gè)字符集。如果沒(méi)有指定字符集,則默認(rèn)使用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;
  }

響應(yīng)緩存

要緩存響應(yīng),你需要一個(gè)進(jìn)行讀取和寫(xiě)入的緩存目錄,以及一個(gè)緩存大小的限制。緩存目錄應(yīng)該是私有的,且不被信任的應(yīng)用不能夠讀取它的內(nèi)容。

讓多個(gè)緩存同時(shí)訪問(wèn)相同的混存目錄是錯(cuò)誤的。大多數(shù)應(yīng)用應(yīng)該只調(diào)用一次new OkHttpClient(),配置它們的緩存,并在所有地方使用相同的實(shí)例。否則兩個(gè)緩存實(shí)例會(huì)相互進(jìn)行干涉,腐朽響應(yīng)緩存,有可能造成你的程序崩潰。

響應(yīng)緩存使用HTTP頭進(jìn)行所有配置。你可以添加像Cache-Control:max-stale=3600這樣的請(qǐng)求頭并且OkHttp的緩存會(huì)尊重它們。你的服務(wù)器使用自己的響應(yīng)頭像Cache-Control:max-age=9600來(lái)配置響應(yīng)緩存多久。這里有緩存頭來(lái)強(qiáng)制一個(gè)緩存響應(yīng),強(qiáng)制一個(gè)網(wǎng)絡(luò)響應(yīng),強(qiáng)制使用一個(gè)條件的GET來(lái)驗(yàn)證網(wǎng)絡(luò)響應(yīng)。

 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來(lái)阻止響應(yīng)使用緩存。使用CacheContril.FORCE_CACHE來(lái)阻止使用網(wǎng)絡(luò)。注意:如果你使用FORCE_CACHE且響應(yīng)需要網(wǎng)絡(luò),OkHttp會(huì)返回一個(gè)504 Unsatisfiable Request響應(yīng)。

取消調(diào)用

使用Call.cancel()來(lái)立即停止一個(gè)正在進(jìn)行的調(diào)用。如果一個(gè)線程正在寫(xiě)請(qǐng)求或讀響應(yīng),它會(huì)接收到一個(gè)IOException。當(dāng)一個(gè)調(diào)用不再需要時(shí),使用這個(gè)來(lái)節(jié)省網(wǎng)絡(luò),例如當(dāng)用戶從應(yīng)用離開(kāi)。同步和異步調(diào)用都可以取消。

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

超時(shí)

使用超時(shí)來(lái)使調(diào)用在當(dāng)另一端沒(méi)有到達(dá)時(shí)失敗。網(wǎng)絡(luò)部分可能是由于連接問(wèn)題,服務(wù)器可用性問(wèn)題或者其他。OkHttp支持連接、讀取和寫(xiě)入超時(shí)。

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

單獨(dú)配置調(diào)用

所有HTTP client配置都存在OkHttpClient中,包括代理設(shè)置,超時(shí)和緩存。當(dāng)你需要改變一個(gè)單獨(dú)call的配置時(shí),調(diào)用OkHttpClient.newBuilder()。這個(gè)會(huì)返回一個(gè)builder,與原始的client共享下共同的連接池,調(diào)度器和配置。在下面的例子中,我們讓一個(gè)請(qǐng)求有500ms的超時(shí)而另一個(gè)有3000ms的超時(shí)。

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

處理認(rèn)證

OkHttp會(huì)自動(dòng)重試未認(rèn)證請(qǐng)求。當(dāng)一個(gè)響應(yīng)為401 Not Authorized時(shí),會(huì)要求Authenticator來(lái)應(yīng)用證書(shū)。Authenticator的實(shí)現(xiàn)應(yīng)該構(gòu)建一個(gè)包含缺失證書(shū)的新請(qǐng)求。如果沒(méi)有證書(shū)可用,返回null來(lái)跳過(guò)重試。

使用Response.challenges()來(lái)獲取所有認(rèn)證挑戰(zhàn)的模式和領(lǐng)域。當(dāng)完成一個(gè)Basic挑戰(zhàn)時(shí),使用Credentials.basic(username,password)來(lái)編碼請(qǐng)求頭。

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

為了避免當(dāng)認(rèn)證無(wú)法工作時(shí)過(guò)多的嘗試,你可以返回null來(lái)放棄。例如,當(dāng)這些明確的證書(shū)已經(jīng)嘗試過(guò)了,你可能想跳過(guò)。

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

你可能也想在達(dá)到應(yīng)用定義的嘗試限制次數(shù)時(shí)跳過(guò)嘗試:

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

上面的代碼依賴這個(gè)responseCount()方法:

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

原文鏈接:
https://github.com/square/okhttp/wiki/Recipes

OkHttp官方文檔系列文章:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容