使用OkHttp包在Android中進行HTTP頭處理的教程_Android

來源:互聯網
上載者:User

HTTP 頭處理
HTTP 頭是 HTTP 要求和響應中的重要組成部分。在建立 HTTP 要求時需要設定一些 HTTP 頭。在得到 HTTP 的響應之後,也會需要對其中包含的 HTTP 頭進行解析。從代碼的角度來說,HTTP 頭的資料結構是 Map<String, List<String>>類型。也就是說,對於每個 HTTP 頭,可能有多個值。但是大部分 HTTP 頭都只有一個值,只有少部分 HTTP 頭允許多個值。OkHttp 採用了簡單的方式來區分這兩種類型,使得對 HTTP 頭的使用更加簡單。
在設定 HTTP 頭時,使用 header(name, value) 方法來設定 HTTP 頭的唯一值。對同一個 HTTP 頭,多次調用該方法會覆蓋之前設定的值。使用 addHeader(name, value) 方法來為 HTTP 頭添加新的值。在讀取 HTTP 頭時,使用 header(name) 方法來讀取 HTTP 頭的最近出現的值。如果該 HTTP 頭只有單個值,則返回該值;如果有多個值,則返回最後一個值。使用 headers(name) 方法來讀取 HTTP 頭的所有值。
下面的代碼中使用 header 方法設定了 User-Agent 頭的值,並添加了一個 Accept 頭的值。在進行解析時,通過 header 方法來擷取 Server 頭的單個值,通過 headers 方法來擷取 Set-Cookie 頭的所有值。

public class Headers {  public static void main(String[] args) throws IOException {  OkHttpClient client = new OkHttpClient();  Request request = new Request.Builder()      .url("http://www.baidu.com")      .header("User-Agent", "My super agent")      .addHeader("Accept", "text/html")      .build();  Response response = client.newCall(request).execute();  if (!response.isSuccessful()) {    throw new IOException("伺服器端錯誤: " + response);  }  System.out.println(response.header("Server"));  System.out.println(response.headers("Set-Cookie"));  }}


Synchronous Get(同步 GET)
下載一個檔案,以字串的形式列印出他的頭部資訊,列印出響應資料體資訊。

String() 方法作為一些小檔案的響應資料體是非常方便和高效的。但是如果針對一些大檔案的下載(大於 1MB 檔案),盡量避免使用 String() 方法因為他會將整個文本載入到記憶體中。針對這種例子優先選擇的解決方案是將資料體作為一個資料流來處理。

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

Asynchronous Get(非同步 GET)
在背景工作執行緒中進行下載任務,並且在響應到達的時候採用回調的方式通知。這個回調會等待響應資訊頭準備好之後發送,讀取這個回應標頭資訊仍然會阻塞。目前的 OKHttp 不支援非同步 APIS 來接收處理部分的響應體。

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(Request request, IOException throwable) {    throwable.printStackTrace();   }   @Override public void onResponse(Response response) throws IOException {    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());   }  }); }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.