·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> Android开发 >> 使用OkHttp包在Android中进行HTTP头处理的教程

使用OkHttp包在Android中进行HTTP头处理的教程

作者:佚名      Android开发编辑:admin      更新时间:2022-07-23

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