Java URLConnection为有效URL返回null

时间:2017-04-19 02:30:41

标签: java yahoo-finance urlconnection

我一直在收集项目的股票市场数据,过去几个月一直这样做。然而,就在几天前,我一直用来从雅虎下载数据的URLConnection已经无效,尽管它没有做任何改变,并且在此之前它已经完美运行了。来自Yahoo的URL下载了我读取并打印出来的csv文件,如果我在浏览器中访问该URL,则该URL有效,但是当我在我的代码中连接它时,URLConnection为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()); 
}

1 个答案:

答案 0 :(得分:2)

使用curl显示该网址已重定向到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

将您的网址更改为使用https而不是http。我做了更改,在代码中的URL中使用https,它对我有用。