Java read CSV file from the web [closed]

2019-07-25 14:58发布

问题:

I'm trying to read a CSV file from the web. Here's the Java code I have written:

String st = "http://finance.yahoo.com/d/quotes.csv?s=NAK&f=sl1c1vd1t1p2hg&e=.csv";
URL stockURL = new URL(st);
BufferedReader in = new BufferedReader(new InputStreamReader(stockURL.openStream()));
String s = null;
while ((s=in.readLine())!=null) {
    System.out.println(s);
}

However, the BufferedReader appears to be empty. When I put the URL in my browser, a CSV file is downloaded which is not an empty file. Any ideas?

回答1:

The server actually sends a 301 response redirecting to http://download.finance.yahoo.com/d/quotes.csv?s=NAK&f=sl1c1vd1t1p2hg&e=.csv. Your browser follows the redirect, but your code does not. If you directly use the final URL, your code works fine.