Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import com.google.gson.*;
- public class Main {
- class StockAPI {
- public String getStockInfo(String tickerSymbl) throws IOException {
- String myAPIurl = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=";
- String myApiToken = "&apikey=UELU6AL4I27DSMI4";
- String stockURL = myAPIurl + tickerSymbl + myApiToken;
- URL url = new URL(stockURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String response = new String();
- for (String line; (line = rd.readLine()) != null; response += line) ;
- String output = parseJsonFunction(response);
- return output;
- }
- //Function that will parse your JSON
- public String parseJsonFunction(String json) {
- JsonObject object = new JsonParser().parse(json).getAsJsonObject();
- JsonObject main = object.getAsJsonObject("Global Quote");
- double open = main.get("02. open").getAsDouble();
- double high = main.get("03. high").getAsDouble();
- double low = main.get("04. low").getAsDouble();
- String day = main.get("07. latest trading day").getAsString();
- String ticker = main.get("01. symbol").getAsString();
- String output = "On the day of " + day + " " + ticker +
- " opened with a stock price of $" + open + " USD. " + ticker +
- " reached a high of $" + high + " USD, and a low of $" + low + " USD.";
- return output;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement