Search code examples
javaurlinputstream

Download file programmatically


I am trying to download an vcalendar using a java application, but I can't download from a specific link.

My code is:

URL uri = new URL("http://codebits.eu/s/calendar.ics");
InputStream in = uri.openStream();

int r = in.read();
while(r != -1) {
    System.out.print((char)r);
    r = in.read();
}

When I try to download from another link it works (ex: http://www.mysportscal.com/Files_iCal_CSV/iCal_AUTO_2011/f1_2011.ics). Something don't allow me to download and I can't figure out why, when I try with the browser it works.


Solution

  • I'd follow this example. Basically, get the response code for the connection. If it's a redirect (e.g. 301 in this case), retrieve the header location and attempt to access the file using that.

    Simplistic Example:

    URL uri = new URL("http://codebits.eu/s/calendar.ics");
    HttpURLConnection con = (HttpURLConnection)uri.openConnection();
    System.out.println(con.getResponseCode());
    System.out.println(con.getHeaderField("Location"));
    
    uri = new URL(con.getHeaderField("Location"));
    con = (HttpURLConnection)uri.openConnection();
    InputStream in = con.getInputStream();