2017-04-19 86 views
0

我一直在收集項目的股票市場數據,並且在過去幾個月一直這樣做。然而,就在幾天前,我一直用來從雅虎下載數據的URLConnection已經爲空,儘管沒有做任何修改,並且在此之前它已經完美運行。來自雅虎的URL下載一個我閱讀並打印出來的csv文件,並且如果我在瀏覽器上訪問該URL,該URL是有效的,然後當我在我的代碼中連接到它時,URLConnection爲空。嘗試與其他股票也沒有幫助。Java URLConnection對於有效的URL返回null

private URL url = null; 
private URLConnection urlConn = null; 
private InputStreamReader inStream = null; 
try { 
     //http://ichart.finance.yahoo.com/table.csv?s=^FTSE&d=3&e=18&f=2017&g=d&a=1&b=14&c=2017 
     this.url = new URL(urlStr); 
        System.out.println(url.toString()); 
     this.urlConn = url.openConnection(); 
     this.urlConn.connect(); 

     //Start Reading 
     this.inStream = new InputStreamReader(this.urlConn.getInputStream()); 
     BufferedReader buff= new BufferedReader(this.inStream); 
     System.out.println(buff.readLine()); 
}catch (MalformedURLException e) { 
     System.out.println(e.getMessage()); 
}catch(IOException e){ 
     System.out.println(e.getMessage()); 
} 
+0

將IOException更改爲Exception以查看是否缺少應該捕獲的異常。這可能是一個403錯誤。 – Sedrick

+1

'URLConnection'是* not * null。 'readLine()'*返回* null,或者拋出異常。準確。 – EJP

回答

2

使用curl顯示URL已被重定向到https。

$ curl -v -H "Content-Type: text/csv" "http://ichart.finance.yahoo.com/table.csv?s=^FTSE&d=3&e=18&f=2017&g=d&a=1&b=14&c=2017" 
* Trying 98.139.199.204... 
* Connected to ichart.finance.yahoo.com (98.139.199.204) port 80 (#0) 
> GET /table.csv?s=^FTSE&d=3&e=18&f=2017&g=d&a=1&b=14&c=2017 HTTP/1.1 
> Host: ichart.finance.yahoo.com 
> User-Agent: curl/7.43.0 
> Accept: */* 
> Content-Type: text/csv 
> 
< HTTP/1.1 301 Moved Permanently 
< Date: Wed, 19 Apr 2017 02:48:29 GMT 
< Via: http/1.1 media-router68.prod.media.bf1.yahoo.com (ApacheTrafficServer [c s f ]), http/1.1 r23.ycpi.bf1.yahoo.net (ApacheTrafficServer [cMsSfW]) 
< Server: ATS 
< Location: https://ichart.finance.yahoo.com/table.csv?s=^FTSE&d=3&e=18&f=2017&g=d&a=1&b=14&c=2017 
< Content-Length: 0 
< Age: 0 
< Connection: keep-alive 
< 
* Connection #0 to host ichart.finance.yahoo.com left intact 

更改您的URL以使用https而不是http。我做了更改,在代碼中的URL中使用https,併爲我工作。

+1

這解決了問題!很簡單。非常感謝! – Fernando

+1

@Fernando:如果這個答案有幫助,請接受它 –