OkHttp - JamesDansie/data-structures-and-algorithms GitHub Wiki

OkHttp

Author: James Dansie

OkHttp is a package for making network connections. It's similar to express in javaScript. It has some built in magic where it will recover from common errors on its own. It will try different IP addresses if the service is unreliable. It will cache repetitive calls. Here is a sample code for getting a string response;

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

To post to a server use;

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

References