João Nunes
João Nunes

Reputation: 711

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.

Upvotes: 1

Views: 261

Answers (3)

speedRS
speedRS

Reputation: 1240

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

Upvotes: 1

morja
morja

Reputation: 8560

I think too that there is a redirect. The browser downloads from ssl secured https://codebits.eu/s/calendar.ics. Try using a HttpURLConnection, it should follow redirects automatically:

HttpURLConnection con = (HttpURLConnection)uri.openConnection();
InputStream in = con.getInputStream();

Upvotes: 0

Miquel
Miquel

Reputation: 15675

You should check what that link actually provides. For example, it might be a page that has moved, which gives you back an HTTP 301 code. Your browser will automatically know to go and fetch it from the new URL, but your program won't.

You might want to try, for example, wireshark to sniff the actual traffic when you do the browser request.

Upvotes: 0

Related Questions