In this post I will explain to you how we can connect to WebSocket in our Android application using OKHttp. In my last post, I will explain how we can use OkHttp in our Android application to get data from API. Now in this post, we can connect to WebSocket using OKHttp. Now without wasting any time, we start building our application.

Step 1. Create a new Android application on the android studio.

Step 2. Install OKHttp library in your project open project app build.gradle and implement OKHttp library

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Step 3. Now open your layout file (main_activity.xml) file and create a button inside as shown below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Load Api"/>

</LinearLayout>

Step 4. Now in this step, we can create a WebSocket in our MainActivity.java. Before creating WebSocket don’t forget to add Internet permission in AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET"/>

For this example, I am using the WebSocket connection of Coinbase. Now we can function in which we can connect to WebSocket.

public void getCoinPrice(final String product) {
    OkHttpClient clientCoinPrice = new OkHttpClient();
    Request requestCoinPrice = new Request.Builder().url(gdaxUrl).build();

    WebSocketListener webSocketListenerCoinPrice = new WebSocketListener() {
        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            webSocket.send("{\n" +
                    "    \"type\": \"subscribe\",\n" +
                    "    \"channels\": [{ \"name\": \"ticker\", \"product_ids\": [\"" + product + "\"] }]\n" +
                    "}");
            Log.e(TAG, "onOpen");
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            Log.e(TAG, "MESSAGE: " + text);
        }

        @Override
        public void onMessage(WebSocket webSocket, ByteString bytes) {
            Log.e(TAG, "MESSAGE: " + bytes.hex());
        }

        @Override
        public void onClosing(WebSocket webSocket, int code, String reason) {
            webSocket.close(1000, null);
            webSocket.cancel();
            Log.e(TAG, "CLOSE: " + code + " " + reason);
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            //TODO: stuff
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            //TODO: stuff
        }
    };

    clientCoinPrice.newWebSocket(requestCoinPrice, webSocketListenerCoinPrice);
    clientCoinPrice.dispatcher().executorService().shutdown();
}

If you ever work with WebSocket you can easily understand above code we have the same function as we have in web socket.

Complete Code of WebSocket Android

package com.websocketsexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.websocketsexample.utility.ServerAsync;
import com.websocketsexample.utility.GetResponse;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class MainActivity extends AppCompatActivity {

    String TAG = "CoinWeb";
    Button id;
    private ServerAsync serverAsync;
    private final String gdaxUrl = "wss://ws-feed.gdax.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        id = (Button) findViewById(R.id.button);

        id.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCoinPrice("ETH-USD");
            }
        });
    }

    public void getCoinPrice(final String product) {
        OkHttpClient clientCoinPrice = new OkHttpClient();
        Request requestCoinPrice = new Request.Builder().url(gdaxUrl).build();

        WebSocketListener webSocketListenerCoinPrice = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                webSocket.send("{\n" +
                        "    \"type\": \"subscribe\",\n" +
                        "    \"channels\": [{ \"name\": \"ticker\", \"product_ids\": [\"" + product + "\"] }]\n" +
                        "}");
                Log.e(TAG, "onOpen");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.e(TAG, "MESSAGE: " + text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                Log.e(TAG, "MESSAGE: " + bytes.hex());
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                webSocket.close(1000, null);
                webSocket.cancel();
                Log.e(TAG, "CLOSE: " + code + " " + reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                //TODO: stuff
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                //TODO: stuff
            }
        };

        clientCoinPrice.newWebSocket(requestCoinPrice, webSocketListenerCoinPrice);
        clientCoinPrice.dispatcher().executorService().shutdown();
    }
}

Hope this post helps you.