OkHttp(三)之使用方法

OKHttp(一)之Calls

OKHttp(二)之Connections

OkHttp(三)之使用方法

OkHttp(四)之?dāng)r截器

OkHttp(五)之HTTPS

Retrofit使用詳解(一)

Retrofit使用詳解(二)

Retrofit使用詳解(三)

Retrofit使用詳解(四)

Retrofit使用詳解(五)

Retrofit使用詳解(六)

一些使用方法:

同步方法Get:

下載一個(gè)文件,打印它的頭信息,打印響應(yīng)體。

response.body的string()方法用來(lái)輸出小型文檔非常方便并且效率非常高。但是假如response.body大于1M,應(yīng)該避免使用string()方法,因?yàn)樗鼘?huì)將整個(gè)文檔加載到內(nèi)存中。此時(shí)使用流更好。

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方法

在工作線程上下載文件,并在響應(yīng)可讀時(shí)調(diào)用毀掉方法。 回調(diào)在響應(yīng)頭準(zhǔn)備好之后進(jìn)行。 讀取響應(yīng)體可能仍會(huì)阻塞線程。 OkHttp目前不提供異步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)頭

通常HTTP的頭信息類似于Map <String,String>:每個(gè)字段有一個(gè)值或?yàn)榭铡?但一些頭允許多個(gè)值,如Guava的Multimap。 例如,HTTP響應(yīng)提供多個(gè)Vary頭是合法且常見的。
在寫入請(qǐng)求標(biāo)頭時(shí),使用header(name,value)將替換頭信息。 如果有現(xiàn)有值,則在添加新值之前將刪除它們。 使用addHeader(name,value)添加頭,而不刪除已經(jīng)存在的頭。

讀取響應(yīng)頭時(shí),使用header(name)返回最后一次的值。如果沒(méi)有值,header(name)將返回null。 要將所有字段的值作為列表讀取,請(qǐng)使用headers(name)。

要訪問(wèn)所有頭,請(qǐng)使用支持通過(guò)索引訪問(wèn)的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();

    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方法傳入字符串

使用HTTP POST將請(qǐng)求正文發(fā)送到服務(wù)器。此示例將markdown文檔發(fā)布到能將markdown轉(zhuǎn)換為HTML的Web服務(wù)器。由于整個(gè)請(qǐng)求主體都在內(nèi)存中,因此請(qǐng)避免使用此API發(fā)布大(大于1個(gè)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發(fā)送流

這里使用POST方法以流的方式發(fā)送請(qǐng)求。請(qǐng)求內(nèi)容將會(huì)一邊生成一邊寫入。 此示例直接流入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());
  }

Post一個(gè)文件

直接看代碼:

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

Post form表單

使用FormBody.Builder構(gòu)建一個(gè)類似于HTML <form>標(biāo)簽的請(qǐng)求體。 名稱和值將使用HTML兼容的表單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());
  }

Post復(fù)雜體請(qǐng)求

MultipartBody.Builder可以構(gòu)建與HTML文件上傳表單兼容的復(fù)雜請(qǐng)求體。 大部分請(qǐng)求正文的每個(gè)部分本身都是請(qǐng)求正文,并且可以定義其自己的頭。 這些頭信息應(yīng)描述內(nèi)容主體,例如其Content-Disposition。 如果Content-Length和Content-Type的header可用,則會(huì)自動(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,用于在JSON和Java對(duì)象之間進(jìn)行轉(zhuǎn)換。 這里我們使用它來(lái)解碼來(lái)自GitHub API的JSON響應(yīng)。

請(qǐng)注意,ResponseBody.charStream()使用Content-Type響應(yīng)頭來(lái)選擇在解碼響應(yīng)正文時(shí)要使用的字符集。 如果沒(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)緩存設(shè)置一個(gè)你自己能夠讀寫的目錄,并且為這個(gè)緩存設(shè)定大小。緩存目錄必須是私有的,不被信任的程序不能訪問(wèn)這個(gè)目錄。

不能使用多個(gè)緩存同時(shí)訪問(wèn)同意緩存目錄。大多數(shù)應(yīng)用程序應(yīng)該只調(diào)用OkHttpClient()一次(就是只創(chuàng)建一個(gè)實(shí)例),否則多個(gè)實(shí)例會(huì)導(dǎo)致程序崩潰,破壞緩存文件。

響應(yīng)緩存對(duì)所有配置使用HTTP頭。 您可以添加請(qǐng)求頭,如Cache-Control:max-stale = 3600,OkHttp的緩存會(huì)使用這些配置。你的網(wǎng)絡(luò)服務(wù)器會(huì)配置響應(yīng)緩存持續(xù)時(shí)間的響應(yīng)頭,如Cache-Control:max-age = 9600。 緩存頭強(qiáng)制緩存響應(yīng),強(qiáng)制網(wǎng)絡(luò)響應(yīng),或強(qiáng)制使用條件GET驗(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));
  }

要防止響應(yīng)使用緩存,請(qǐng)使用CacheControl.FORCE_NETWORK。 為了防止它使用網(wǎng)絡(luò),請(qǐng)使用CacheControl.FORCE_CACHE。

Note
:如果使用FORCE_CACHE并且響應(yīng)需要網(wǎng)絡(luò),OkHttp將返回504 Unsatisfiable Request響應(yīng)。

取消請(qǐng)求

使用Call.cancel()方法來(lái)立即他停止一個(gè)正在進(jìn)行的請(qǐng)求。如果一個(gè)線程正在寫入一個(gè)請(qǐng)求或者讀取一個(gè)響應(yīng),程序?qū)?huì)拋出IOException異常。使用此選項(xiàng)可在不再需要call時(shí)節(jié)約網(wǎng)絡(luò)資源。 例如當(dāng)您的用戶導(dǎo)航離開應(yīng)用程序時(shí),同步和異步調(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í)

當(dāng)連接不可達(dá)時(shí)使用timeouts來(lái)使一個(gè)請(qǐng)求失敗。連接問(wèn)題,服務(wù)器問(wèn)題或者其他都可能導(dǎo)致網(wǎng)絡(luò)連接失敗,OhHttp支持連接超時(shí),讀超時(shí)和寫超時(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ú)配置

所有HTTP客戶端配置都存在于OkHttpClient中,包括代理設(shè)置,超時(shí)和緩存。 當(dāng)您需要更改單個(gè)調(diào)用的配置時(shí),請(qǐng)調(diào)用OkHttpClient.newBuilder()。 這將返回與原始客戶端共享的相同連接池,調(diào)度程序和配置的構(gòu)建器。 在下面的示例中,我們使用500毫秒超時(shí)創(chuàng)建一個(gè)請(qǐng)求,另一個(gè)請(qǐng)求使用3000毫秒超時(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可以自動(dòng)重試未經(jīng)身份驗(yàn)證的請(qǐng)求。 當(dāng)響應(yīng)為401 Not Authorized,將要求Authenticator提供憑據(jù)。 應(yīng)構(gòu)建新請(qǐng)求包含憑證, 如果沒(méi)有可用的憑據(jù),則返回null以跳過(guò)重試。

使用Response.challenges()獲取任何身份驗(yàn)證的方案和領(lǐng)域。 當(dāng)完成基本挑戰(zhàn)時(shí),使用Credentials.basic(username,password)對(duì)請(qǐng)求標(biāo)頭進(jìn)行編碼。

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

你可以返回空值來(lái)放棄一個(gè)認(rèn)證不通過(guò)的請(qǐng)求,避免多次重復(fù)本請(qǐng)求。例如,你可能想要跳過(guò)那些已經(jīng)嘗試過(guò)的請(qǐng)求。

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

你也可以跳過(guò)服務(wù)器拒絕的請(qǐng)求:

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;
  }
最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,789評(píng)論 25 709
  • 參考Android網(wǎng)絡(luò)請(qǐng)求心路歷程Android Http接地氣網(wǎng)絡(luò)請(qǐng)求(HttpURLConnection) 一...
    合肥黑閱讀 21,697評(píng)論 7 63
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • OkHttp使用完全教程 標(biāo)簽 : Http請(qǐng)求, 類庫(kù)blog : http://blog.csdn.net/o...
    oncealong閱讀 171,489評(píng)論 27 460
  • 說(shuō)起我的高三,首先回想起來(lái)的居然不是做不完的作業(yè),背不完的課文,而是一部電影和一首歌。 那部電影叫做死亡詩(shī)社。 我...
    卿水阿琳閱讀 569評(píng)論 0 0

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