Search code examples
javaapiwebsocketjava-websocket

How to get a specific Value or Data using the API in Java


Sorry if the question is a bit simple. I am new to this and i am currently trying to fetch some values using a websites API. I will drop a link below. Here is the issue. The code i have is the exact code the website provided. I want to take the "quote" values only from the result sent from them. Here is the code:

import java.net.URI;
import java.io.IOException;
import java.lang.InterruptedException;
import javax.websocket.*;

@ClientEndpoint
public class WSClient  {

@OnOpen
public void onOpen(Session session) throws java.io.IOException
{
    session.getBasicRemote().sendText("{\"ticks\": \"R_100\"}");
}

@OnMessage
public void onMessage(String message)
{
    System.out.println("ticks update: " + message);
}

public static void main(String[] args)
    throws IOException, DeploymentException, InterruptedException
{
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3");
    Session session = container.connectToServer(WSClient.class, apiUri);
    Thread.sleep(3000);
}
}

And here is the result on my Console in eclipse:

ticks update: {"echo_req":{"ticks":"R_100"},"tick":{"epoch":"1461413058","symbol":"R_100","quote":"37673.45","id":"810945BC-094B-11E6-B438-8E7300DB46A6"},"msg_type":"tick"}

The results works fine but i want to take just the "quote" Value which is a numeric value.

Here is the link to their API Website / Dev Website: https://developers.binary.com/

Thank you in Advance :)


Solution

  • Your response looks like a JSON string you should just do this

    @OnMessage
    public void onMessage(String message)
        JSONObject response = new JSONObject(message);
        int quote = Integer.parseInt(response.getString("quote"));
    }