Karlovsky120
Karlovsky120

Reputation: 6362

java and website redirection detection

I have java related question...

Website www.stationv3.com gets updated daily (most of the time at least, it's kinda irregular). Every time I connect to a site using address www.stationv3.com (using a browser), it redirects me to it's subpage www.stationv3.com/date_of_latest_update.html

I'm trying to make a program that will pull latest comic from the site, but I am not sure how to find out it's exact address. But I know I'd be able to find out if I could somehow find out where where am I being redirected on every connect. Is that possible with java? I know it can do all sorts of quirky things, but I'm still new to internet related stuff...

I used exact site name just to make it easy for you to check outwhat's going on... And also, I'm creating a generic code, one which could (with some tinkering) be applyed to any site that functions in that manner.

Upvotes: 1

Views: 393

Answers (2)

loscuropresagio
loscuropresagio

Reputation: 1952

I think you could just fecth:

http://www.stationv3.com/comics/{yyyy}{mm}{dd}sv3.gif

and forget about the redirection problem. You can use this code (not tested indeed):

URL server = new URL("<put here the image URL>");
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();       
OutputStream os = new FileOutputStream("c:/mycomic.gif");

byte[] buffer = new byte[1024];     
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
    os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}

os.close();

Upvotes: 0

Piyush Mattoo
Piyush Mattoo

Reputation: 16143

import java.net.*;
public class ShowStationV3Redirect {
public static void main(String[] args) throws Exception {
    URL url = new URL(args[0]);
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    System.out.println("Response code = " + connection.getResponseCode());
    String header = connection.getHeaderField("location");
    if (header != null)
        System.out.println("www.stationv3.com redirected to " + header);
}
}

The above code snippet tells you what URL you are being redirected to.

Upvotes: 2

Related Questions