2017-04-19 81 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:如果这个答案有帮助,请接受它 –