Features
– HTTP/2 support
– Google SPDY (“speedy”) support: Reduces latency through compression, multiplexing and prioritization; However, SPDY will be deprecated in the future since HTTP/2 will handle what SPDY would have done
– Silently recovers from common connection problems
– If there are multiple IP addresses/redundant data centers, it will fall back to alternate address if the previous connection fails.
– Uses modern Transport Layer Security (TLS) and falls back to TLS 1.0. TLS is the successor to SSL
– Server Name Indication (TLS extension): Allows clients to connect multiple SSL Certificates so that the administrator don’t have to have IP’s for the individual certificates
– Application-Layer Protocol Negotiation (TLS extension): Used by HTTP/2; Allows the applications to determine which protocol should be used in a secure connection that reduces subsequent round trips

GET a URL
1) Instantiate OkHttpClient
2) Build request
3) Pass the request to client and invoke .execute()
4) Obtain response through response.body().string();

OkHttpClient client = new OkHttpClient();

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

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

POST to the server
1) Instantiate OkHttpClient
2) Create MediaType
3) Create RequestBody object. First parameter is the Media Type, the second parameter is the payload that will be in the Request
4) Using Request.Builder(), a) set the server’s end point, b) add the request body to the post(), and finally c) build the request
5) Pass the request to client and invoke .execute()
6) Obtain response through response.body().string();

public static final MediaType JSON
    = MediaType.parse("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();
  Response response = client.newCall(request).execute();
  return response.body().string();
}
Share

Google+ Comments