Sample code for 30+ languages & platforms
Java Requires Chilkat v11.4.0+

Finnhub API - Get Stock Quote

See more AI Examples

Demonstrates how to get a stock quote from the Finnhub API.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpRequest;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        // Replace with your actual Finnhub API key.
        String apiKey = "YOUR_FINNHUB_API_KEY";
        String symbol = "AAPL";

        Http http = new Http();

        // This is the URL without params.
        String urlWithoutParams = "https://finnhub.io/api/v1/quote";

        HttpRequest req = new HttpRequest();

        // Add params that will be sent in the URL.
        req.addParam("symbol", symbol);
        req.addParam("token", apiKey);

        req.setHttpVerb("GET");

        // Send the request to get the JSON response.
        HttpResponse resp = new HttpResponse();
        try {
            http.httpReq(urlWithoutParams, req, resp);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        JsonObject json = new JsonObject();
        resp.getBodyJson(json);

        int statusCode = resp.getStatusCode();
        System.out.println("response status code: " + statusCode);

        json.setEmitCompact(false);
        System.out.println(json.emit());

        // Sample result:

        // {
        //   "c": 248.8,
        //   "d": -4.09,
        //   "dp": -1.6173,
        //   "h": 255.493,
        //   "l": 248.07,
        //   "o": 253.9,
        //   "pc": 252.89,
        //   "t": 1774641600
        // }

        if (statusCode == 200) {
            // Add the symbol to the top of the result.
            json.addStringAt(0, "symbol", symbol);

            // Rename members for clarification.
            json.rename("c", "currentPrice");
            json.rename("d", "change");
            json.rename("dp", "percentChange");
            json.rename("h", "high");
            json.rename("l", "low");
            json.rename("o", "open");
            json.rename("pc", "prevClose");
            json.rename("t", "unixTime");

            System.out.println(json.emit());
        } else {
            System.out.println("Failed");
        }
    }
}