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

Unlike the traditional request/response model of HTTP, web sockets provide fully bi-directional streaming of messages. This means that both the client and the server can send any number of messages to the other peer at any time. With today’s version 3.5 release, OkHttp now offers native support for web sockets!

Connect a web socket by passing a request to the newWebSocket() method along with a listener for server-sent messages.

OkHttpClient client = new OkHttpClient(); Request request = //...

WebSocketListener listener = //... WebSocket ws = client.newWebSocket(request, listener);

Enqueue text or binary messages by calling send(String) or send(ByteString) , respectively. Because OkHttp uses its own thread for sending messages, you can call send from any thread (even Android’s main thread).

Messages received from the server will be delivered to the listener’s onMessage callback as a String or ByteString . The listener also has callbacks which notify you of the connection lifecycle.

We’re excited to finally be able to share a stable web socket API in OkHttp. Use version 3.5 in your app by adding the following to your build.gradle :

compile 'com.squareup.okhttp3:okhttp:3.5.0

The full change log for this version is available here.