Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to find the redirected url of a url?

I am accessing web pages through java as follows:

URLConnection con = url.openConnection(); 

But in some cases, a url redirects to another url. So I want to know the url to which the previous url redirected.

Below are the header fields that I got as a response:

null-->[HTTP/1.1 200 OK] Cache-control-->[public,max-age=3600] last-modified-->[Sat, 17 Apr 2010 13:45:35 GMT] Transfer-Encoding-->[chunked] Date-->[Sat, 17 Apr 2010 13:45:35 GMT] Vary-->[Accept-Encoding] Expires-->[Sat, 17 Apr 2010 14:45:35 GMT] Set-Cookie-->[cl_def_hp=copenhagen; domain=.craigslist.org; path=/; expires=Sun, 17     Apr 2011 13:45:35 GMT, cl_def_lang=en; domain=.craigslist.org; path=/; expires=Sun, 17 Apr 2011 13:45:35 GMT] Connection-->[close] Content-Type-->[text/html; charset=iso-8859-1;] Server-->[Apache] 

So at present, I am constructing the redirected url from the value of the Set-Cookie header field. In the above case, the redirected url is copenhagen.craigslist.org

Is there any standard way through which I can determine which url the particular url is going to redirect.

I know that when a url redirects to other url, the server sends an intermediate response containing a Location header field that tells the redirected url but I am not receiving that intermediate response through the url.openConnection(); method.

like image 356
Yatendra Avatar asked Apr 17 '10 15:04

Yatendra


People also ask

How do I find redirect IP address?

If you're not sure whether such a redirect already exists, you can run the Sitechecker tool's IP canonicalization test. It displays whether your domain redirects to a domain name that you specify. Use an IP address checker to see what your exact public IP address is — IPv4 or IPv6.

How do I find a 301 redirect?

Simply head to Analytics and follow this path: HTTP Codes, Top Charts, HTTP Status Codes Distribution or Insights, and then click 301 URLs in the pie chart. There are also a variety of other ways you can navigate to your 301s within Analytics and URL Explorer.


1 Answers

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL( url ).openConnection(); System.out.println( "orignal url: " + con.getURL() ); con.connect(); System.out.println( "connected url: " + con.getURL() ); InputStream is = con.getInputStream(); System.out.println( "redirected url: " + con.getURL() ); is.close(); 

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection()); con.setInstanceFollowRedirects( false ); con.connect(); int responseCode = con.getResponseCode(); System.out.println( responseCode ); String location = con.getHeaderField( "Location" ); System.out.println( location ); 
like image 104
amobiz Avatar answered Oct 31 '22 14:10

amobiz