24 Apr 2013, 16:53

Trying out Square's OkHttp client


Trying out Square’s OkHttp client

This is a simple example of implementing Square’s OkHttp library in an Android app. Basically, OkHttp is intending to provide a fast HTTP+SPDY java client.


Step zero is getting OkHttp either as a jar, or pulling down the project and building a jar with maven. When I built this, the jar was not available, so I needed to build it myself. This was quite simple, all you need to do is make sure you have Maven2 installed, and follow the instructions on OkHttp’s github page.

One thing to note is that you need to be building against the parent project, not just the okhttp dir. Sometimes people package up git repos such that there are actually multiple projects in a single repo, and you only need to use one of the dirs in the project. In this case, you need the parent, it will build the child projects for you.


mvn clean
mvn package -DskipTests

After you build, the jar will be in okhttp/targets.

This git repo bundles a version of okhttp that I build, but it would be better to pull down a more recent version.


I’m also using Otto here. Check out my post on Otto for a quick primer.

Onto the code!

First up, since we’re using Otto, we register with the bus first. Then, the OkHttp logic is placed in an AsyncTask, so we’ll kick that off here too. This code lives in an Activity’s onCreate.

Here’s the logic for connecting to a site, reading the response into a string, and sending a message out onto the bus with that response string.

This is the method that’s subscribing to the bus, waiting for that response string.

Check out the full project here.

comments powered by Disqus