hozer

YAHOO finance API

Jul 13th, 2015
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.30 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URL;
  6. import java.net.URLEncoder;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. import java.util.Objects;
  11.  
  12. public class Quotes {
  13.  
  14.     public String[][] get(String[] id, String[] properties) {
  15.         List<List<String>> quotesList = new ArrayList<>();
  16.         String[][] quotes;
  17.         try {
  18.             URL q_endpoint = new URL(buildUrl(id, properties));
  19.             BufferedReader in = new BufferedReader(new InputStreamReader(q_endpoint.openStream()));
  20.  
  21.             String inputLineTmp;
  22.             while ((inputLineTmp = in.readLine()) != null && !Objects.equals(inputLineTmp, "")) {
  23.                 quotesList.add(Arrays.asList(inputLineTmp.split(",")));
  24.             }
  25.  
  26.         } catch (IOException e) {
  27.             e.printStackTrace();
  28.         }
  29.  
  30.         quotes = new String[quotesList.size()][];
  31.         for (int i = 0; i < quotesList.size(); i++) {
  32.             List<String> quote = quotesList.get(i);
  33.             quotes[i] = quote.toArray(new String[quote.size()]);
  34.         }
  35.  
  36.         return quotes;
  37.     }
  38.  
  39.     private String buildUrl(String id[], String[] properties) {
  40.         String url = "http://finance.yahoo.com/d/quotes.csv";
  41.         //add and encode ids to the url
  42.         try {
  43.             if (id.length != 0) {
  44.             url += "?s=";
  45.             for (int i = 0; i < id.length; i++) {
  46.                 url += URLEncoder.encode(id[i], "UTF-8");
  47.                 if (i != id.length - 1) url += ',';
  48.             }
  49.         }
  50.         } catch (UnsupportedEncodingException e) {
  51.             e.printStackTrace();
  52.         }
  53.  
  54.         //add to url properties
  55.         if (properties.length != 0) {
  56.             url += "&f=";
  57.             for (int i = 0; i < properties.length; i++) {
  58.                 url += properties[i];
  59.                 if (i != properties.length - 1) url += ',';
  60.             }
  61.         }
  62.  
  63.         //add static part
  64.         url += "&e=.csv";
  65.         return url;
  66.     }
  67.  
  68.     public static void main(String[] args) {
  69.         Quotes q = new Quotes();
  70.         String[][] o = q.get(new String[] {"GOOG"}, new String[]{"nsl1op"});
  71.         System.out.println(Arrays.toString(o));
  72.     }
  73. }
Add Comment
Please, Sign In to add comment