OkHttp Java 网络客户端


概述

HTTP是现代应用网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以加快您的负载并节省带宽。

OkHttp是一个默认有效的HTTP客户端:

  • HTTP / 2支持允许对同一主机的所有请求共享套接字。
  • 连接池减少了请求延迟(如果HTTP / 2不可用)。
  • 透明GZIP缩小了下载大小。
  • 响应缓存完全避免网络重复请求。

当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中无声地恢复。如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0。

使用OkHttp很简单。它的请求/响应API采用流畅的构建器和不变性设计。它支持同步阻塞调用和带回调的异步调用。

OkHttp支持Android 2.3及更高版本。对于Java,最低要求是1.7。

实例

发送Get请求

package okhttp3.guide;

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetExample {
  OkHttpClient client = new OkHttpClient();

  String run(String url) throws IOException {
    Request request = new Request.Builder()
        .url(url)
        .build();

    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  public static void main(String[] args) throws IOException {
    GetExample example = new GetExample();
    String response = example.run("https://www.codingdict.com/README.txt");
    System.out.println(response);
  }
}

发送Post请求

package okhttp3.guide;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostExample {
  public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

  OkHttpClient client = new OkHttpClient();

  String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  String bowlingJson(String player1, String player2) {
    return "{'winCondition':'HIGH_SCORE',"
        + "'name':'Bowling',"
        + "'round':4,"
        + "'lastSaved':1367702411696,"
        + "'dateStarted':1367702378785,"
        + "'players':["
        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
        + "]}";
  }

  public static void main(String[] args) throws IOException {
    PostExample example = new PostExample();
    String json = example.bowlingJson("Jesse", "Jake");
    String response = example.post("http://www.codingdict.com/post", json);
    System.out.println(response);
  }
}