OkHttp library

OkHttp is an HTTP client that’s efficient by default:

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

Also OkHttp perseveres when the network is troublesome and try to resolve problems.

You can use single client for multiple requests. You can use client with default settings or create client via builder with custom settings.

Library page on GitHub. Official doc has useful recipes.

Add dependency

implementation("com.squareup.okhttp3:okhttp:4.9.1")

GET request

OkHttpClient client = new OkHttpClient();
//...
Request request = new Request.Builder()
      .url(url)
      .build();

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

POST resquest

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