1. Overview
This tutorial is going to cover how to create a WebSocket client example with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.
2. Preparation
We’re going to use OkHttp3, version 3.5.0 for the example.
1 2 3 4 5 |
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.5.0</version> </dependency> |
3. WebSocket Client Example with OkHttp
In this section, we’re going to create a WebSocket client which will connect to the websocket.org, an online service to test WebSocket-based applications and services.
Firstly, let’s see the newWebSocket method which is offered by the OkHttpClient class , use request to connect a new web socket:
1 |
WebSocket okhttp3.OkHttpClient.newWebSocket(Request request, WebSocketListener listener) |
Because the method requires an instance of the Request class and an instance of the WebSocketListener class as parameters in order to create a WebSocket, we’re going to create those objects step by step.
3.1. Create an instance of the WebSocketListener
Because the WebSocketListener is an abstract class, we should extend it first before we can create an instance of it. Let’s see an example how we extend it by our EchoWebSocketListener class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public final class EchoWebSocketListener extends WebSocketListener { private static final int NORMAL_CLOSURE_STATUS = 1000; @Override public void onOpen(WebSocket webSocket, Response response) { webSocket.send("Knock, knock!"); webSocket.send("Hello!"); webSocket.send(ByteString.decodeHex("deadbeef")); webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye!"); } @Override public void onMessage(WebSocket webSocket, String text) { System.out.println("Receiving: " + text); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { System.out.println("Receiving: " + 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(); } } |
Here are a few notes for the above methods:
- The onOpen method is invoked when a web socket has been accepted by the remote peer and may begin transmitting messages. In this example, we will send 3 messages to the remote WebSocket service and then close our client.
- The onMessage methods are invoked when a message has been received. The first method is used for text messages while the second is used for binary messages.
- The onClosing method is invoked when the peer has indicated that no more incoming messages will be transmitted. Notice that we have passed the status code 1000 to imply that the closing is normal closure. You can find more status codes on Section 7.4 of RFC 6455.
- The onFailure method is invoked when a web socket has been closed due to an error reading from or writing to the network.
3.2. Create an instance of the Request class
Create an instance of the Request class is pretty simple. Let’s see an example as below:
1 2 3 |
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("ws://echo.websocket.org").build(); |
We have just created an request the WebSocket service we’re going to test in tutorial.
3.3. Put it all together
Let’s create a class with a main method to test our source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class WebSocketClientTest { public static void main(String... args) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("ws://echo.websocket.org").build(); EchoWebSocketListener listener = new EchoWebSocketListener(); WebSocket ws = client.newWebSocket(request, listener); // Trigger shutdown of the dispatcher's executor so this process can // exit cleanly. client.dispatcher().executorService().shutdown(); } } |
Running the example will print out the following messages into the console:
1 2 3 4 |
Receiving: Knock, knock! Receiving: Hello! Receiving: deadbeef Closing: 1000 Goodbye! |
4. Conclusion
The tutorial has shown you how to create a WebSocket client example with OkHttp. This feature is useful for us to create application that support fully bi-directional streaming of messages between client and server.
The example source code can be found on the Github project or you can download it by clicking on java-examples.zip. It is an Maven-based project, so it will be easy for you to import it into IDEs such as Eclipse, Intellij, etc.
5. Reference
Java REST Client Examples Using OkHttp
Basic Authentication with OkHttp Example
How to Cache Response with OkHttp