YQLをjavaから呼ぶ
やっとjavaからYQLを呼ぶ。
Gsonには活躍してもらう。
URL中の空白(半角スペース)をURLエンコードせずに、実行すると
java.net.SocketException: Unexpected end of file from server at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at QuerySender.sendQuery(QuerySender.java:47) at QuerySender.main(QuerySender.java:19)
という例外が発生した。3時間悩んだよ。
NG…(%22AAPL%22, %20%22VTI%22)
OK…(%22AAPL%22,%20%22VTI%22)
public void sendQuery() { HttpURLConnection con = null; try { URL url = new URL("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22,%20%22VTI%22)&format=json&env=store%3a%2f%2fdatatables.org%2falltableswithkeys"); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setInstanceFollowRedirects(false); con.setRequestProperty("Accept-Language", "ja,en-US;q=0.8,en;q=0.6"); con.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));) { Gson gson = new Gson(); Root root = gson.fromJson(reader, Root.class); for (Quote quote : root.getQuery().getResults().getQuote()) { System.out.println("symbol => " + quote.getSymbol() + ", Ask => " + quote.getAsk() + ", Bid => " + quote.getBid()); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { con.disconnect(); } }