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.

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:

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:

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:

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:

Running the example will print out the following messages into the console:

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

OkHttp on Github

Java REST Client Examples Using OkHttp

Basic Authentication with OkHttp Example

Upload a File with OkHttp

Set Timeout with OkHttp

Download a File with OkHttp

How to Cache Response with OkHttp

 

 

5 1 vote
Article Rating