OkHttpClient的使用方法

参考资料

https://github.com/square/okhttp/wiki
https://github.com/square/okhttp/wiki/Recipes

使用方法

get

// 获取OkHttpClient
private final OkHttpClient client = new OkHttpClient();
// 执行方法
public void run() throws Exception {
    // 建立Builder
    Request request = new Request.Builder()
        .url("https://publicobject.com/helloworld.txt")
        .build();
    // 请求
    try (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());
    }
  }

你可能感兴趣的:(java,okhttp)