Java URLConnection 为有效 URL 返回 null [英] Java URLConnection returns null for valid URL

查看:33
本文介绍了Java URLConnection 为有效 URL 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为一个项目收集股票市场数据,并且在过去几个月一直在这样做.然而,就在几天前,我一直用来从雅虎下载数据的 URLConnection 一直为空,尽管没有进行任何更改并且在此之前它运行良好.来自雅虎的 URL 下载了一个我读取并打印出来的 csv 文件,如果我在浏览器上访问它,该 URL 是有效的并且有效,但是当我在我的代码中连接到它时,URLConnection 为空.尝试其他股票也无济于事.

I've been collecting stock market data for a project, and have been doing so for the past few months. However, as of a couple of days ago the URLConnection I've been using to download data from Yahoo has been null, despite having made no changes and it having worked perfectly before that. The URL from Yahoo downloads a csv file which I read and print out, and the URL is valid and works if I go to it on my browser, yet when I connect to it in my code, the URLConnection is null. Trying with other stocks also hasn't helped.

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()); 
}

推荐答案

使用 curl 显示 URL 已重定向到 https.

Using curl shows that the URL has been redirected to 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 并且对我有用.

Change your URL to use https instead of http. I made the change to use https in the URL within your code and it worked for me.

这篇关于Java URLConnection 为有效 URL 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆