Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.HttpURLConnection;
  5. import java.net.MalformedURLException;
  6. import java.net.URL;
  7. import com.google.gson.*;
  8.  
  9. public class Main {
  10.  
  11. class StockAPI {
  12. public String getStockInfo(String tickerSymbl) throws IOException {
  13. String myAPIurl = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=";
  14. String myApiToken = "&apikey=UELU6AL4I27DSMI4";
  15.  
  16. String stockURL = myAPIurl + tickerSymbl + myApiToken;
  17. URL url = new URL(stockURL);
  18. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  19. conn.setRequestMethod("GET");
  20. BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  21.  
  22. String response = new String();
  23. for (String line; (line = rd.readLine()) != null; response += line) ;
  24.  
  25. String output = parseJsonFunction(response);
  26. return output;
  27. }
  28.  
  29. //Function that will parse your JSON
  30. public String parseJsonFunction(String json) {
  31. JsonObject object = new JsonParser().parse(json).getAsJsonObject();
  32.  
  33. JsonObject main = object.getAsJsonObject("Global Quote");
  34. double open = main.get("02. open").getAsDouble();
  35. double high = main.get("03. high").getAsDouble();
  36. double low = main.get("04. low").getAsDouble();
  37. String day = main.get("07. latest trading day").getAsString();
  38. String ticker = main.get("01. symbol").getAsString();
  39.  
  40. String output = "On the day of " + day + " " + ticker +
  41. " opened with a stock price of $" + open + " USD. " + ticker +
  42. " reached a high of $" + high + " USD, and a low of $" + low + " USD.";
  43. return output;
  44. }
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement