Connect to Web Socket From Your Android App using OkHttp
OkHttp is a widely used HTTP client for Android and Java that also provides first-class WebSocket support. It is the simplest way to add real-time bidirectional communication to an Android application without pulling in a heavy third-party library.
This guide walks through connecting to a WebSocket server from Android using OkHttp3.
Step 1: Add the Dependency
Add OkHttp to your app-level build.gradle file:
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
Sync the project after adding the dependency.
Step 2: Create a WebSocket Listener
Create a class that extends WebSocketListener. This listener handles all WebSocket lifecycle events — connection open, messages received, connection closing, and failures.
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
public final class MyWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
// Connection established — send an initial message if needed
webSocket.send("Hello from Android");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
// Text message received from the server
System.out.println("Received: " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
// Binary message received from the server
System.out.println("Received bytes: " + bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
System.out.println("Closing: " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
t.printStackTrace();
}
}
Step 3: Open the WebSocket Connection
Build an OkHttpClient, create a Request pointing to your WebSocket endpoint, and open the connection with your listener:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("ws://your-server-address:PORT")
.build();
MyWebSocketListener listener = new MyWebSocketListener();
WebSocket webSocket = client.newWebSocket(request, listener);
For Kotlin:
val client = OkHttpClient()
val request = Request.Builder()
.url("ws://your-server-address:PORT")
.build()
val listener = MyWebSocketListener()
val webSocket = client.newWebSocket(request, listener)
Step 4: Send Messages
Once the connection is open (inside onOpen or anywhere you hold a reference to the WebSocket instance), send messages:
webSocket.send("Your message here");
Step 5: Close the Connection
When you no longer need the connection, close it gracefully:
webSocket.close(1000, "Done");
client.dispatcher().executorService().shutdown();
Notes
- WebSocket callbacks run on a background thread. Update UI elements using
runOnUiThread()or aHandler. - For secure connections, use
wss://instead ofws://— OkHttp handles the TLS handshake automatically. - On Android 9 and above, cleartext
ws://connections are blocked by default. Usewss://in production or configureandroid:usesCleartextTraffic="true"for testing only.
Conclusion
OkHttp's WebSocket support requires minimal setup. Define a listener, open a connection with a request, and your Android app can send and receive real-time messages with a few lines of code. The same OkHttpClient instance you use for HTTP requests handles WebSocket connections, keeping your dependency footprint small.