PUBLIC OBJECT

OkHttp 2.2 has Interceptors

When Josh Bloch measures an API, he evaluates its power to weight ratio: great APIs let you accomplish a lot (high power) without much mechanism (lightweight).

Interceptors are a new feature of OkHttp 2.2. There isn't much mechanism: two interfaces and four methods:

public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();
    Response proceed(Request request) throws IOException;
    Connection connection();
  }
}

Use OkHttp's interceptors to hook into your application's HTTP calls. You get to see everything that's coming in and going out to the application (that's an application interceptor). Plus what goes out to and back in from the network (that's a network interceptor).

There is a dangerous amount of power here. Like magic, incredible cosmic power can accomplish great things when it is used carefully:

  • You can throttle incoming and outgoing bandwidth.
  • You can rewrite requests to compress them or sign them.
  • You can collect profiling data.
  • You can validate responses.
  • You can transform the response to workaround server problems.

And like magic, you can get yourself into trouble. Be careful! Read the interceptors doc and code examples to learn how it all works before you dive in.

Get it

The changelog has full details of what's new & what's been fixed. Get 2.2.0 from Maven Central:

<dependency>  
  <groupId>com.squareup.okhttp</groupId>
  <artifactId>okhttp</artifactId>
  <version>2.2.0</version>
</dependency>