OkHttp 2.0

Square’s HTTP client for Android and Java has a new API.

Square Engineering
Jun 23, 2014 · 3 min read

Written by Jesse Wilson.

Heads up, we’ve moved! If you’d like to continue keeping up with the latest technical content from Square please visit us at our new home https://developer.squareup.com/blog

OkHttp started as a fork of Android’s HttpURLConnection. That gave us a solid foundation to build upon. Working behind a widely-used API meant that upgrading from AOSP’s HttpURLConnection to ours was easy: just configure URLs stream handler factory.

But we’ve outgrown the HttpURLConnection API. Its fully-synchronous API means that application code needs to manage how requests are dispatched. Requests and responses are together in one class which makes certain operations awkward or inefficient. Most painfully, we’re limited in what we can expose: Was my request redirected? Did the response come from a cache? OkHttp knows the answers to these questions but the HttpURLConnection API offers no way for you to ask them.

Request, Response, and Call

private final OkHttpClient client = new OkHttpClient();public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Call call = client.newCall(request);
Response response = call.execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
System.out.println(response.body().string());
}

Or asynchronously with a callback:

Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override public void onFailure(Request request, IOException e) {
logger.log(Level.SEVERE, "Failed to execute " + request, e);
}
@Override public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
System.out.println(response.body().string());
}
});

A Request’s Journey

Following Redirects

> GET http://repository.sonatype.org/.../redirect?a=okhttp&v=LATEST< 301 Moved Permanently
< Location: https://repository.sonatype.org/.../redirect?a=okhttp&v=LATEST

Next we’re redirected from the LATEST tag to the specific file we want.

> GET https://repository.sonatype.org/.../redirect?a=okhttp&v=LATEST< 307 Temporary Redirect
< Location: https://repository.sonatype.org/.../content/.../okhttp-2.0.0.jar

Finally we download the file. The response includes headers to make caching possible.

> GET https://repository.sonatype.org/.../content/.../okhttp-2.0.0.jar< 200 OK
< Last-Modified: Sat, 21 Jun 2014 01:00:00 GMT
< ETag: "{SHA1{4c8d1536dba3812cc1592090dc20c47a4ed3c35e}}"

OkHttp exposes these redirects with Response.priorResponse(). If you’re redirected multiple times, you will have a chain of prior responses. These will be returned in order from last-to-first; reverse them for chronological order:

List<Response> chainedResponses = new ArrayList<>();
for (Response r = response; r != null; r = r.priorResponse()) {
chainedResponses.add(r);
}
Collections.reverse(chainedResponses);
for (Response r : chainedResponses) {
System.out.println(r.request().url());
}

Cache and Network Responses

When downloading a jar file from Maven Central, Response.cacheResponse()returns the cached response from above:

> GET https://repository.sonatype.org/.../content/.../okhttp-2.0.0.jar< 200 OK
< Last-Modified: Sat, 21 Jun 2014 01:00:00 GMT
< ETag: "{SHA1{4c8d1536dba3812cc1592090dc20c47a4ed3c35e}}"

This cached response required validation from the server. OkHttp needed to ask, “Has the cached value changed?” Checking Response.networkResponse() confirms that it had not:

> GET https://repository.sonatype.org/.../content/.../okhttp-2.0.0.jar
> If-Modified-Since: Sat, 21 Jun 2014 01:00:00 GMT
> If-None-Match: "{SHA1{4c8d1536dba3812cc1592090dc20c47a4ed3c35e}}"
< 304 Not Modified

Prior responses from redirects also support cacheResponse() and networkResponse(). Use this to interrogate whether any part of a response used the network.

Upgrading to OkHttp 2.0

Get OkHttp from Maven or download it from the project website. Read more code examples in the project’s Recipes doc.

Square Corner Blog

Buying and selling sound like simple things - and they…

Square Corner Blog

Buying and selling sound like simple things - and they should be. Somewhere along the way, they got complicated. At Square, we're working hard to make commerce easy for everyone.

Square Engineering

Written by

The official account for @Square Engineering.

Square Corner Blog

Buying and selling sound like simple things - and they should be. Somewhere along the way, they got complicated. At Square, we're working hard to make commerce easy for everyone.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store