15

I have an authentication protected url : www.domain.com/alias

that when requested will return another url: www.another.com/resource.mp4 (not protected)

I would like to know if exists a method in Java that will return the real url from a given one. Something like: second = resolve(first)

I'm thinking of loading the first and try to read into the response maybe the location attribute, but since I'm not a java guru I would like to know if Java already faces this.

sosergio
  • 944
  • 2
  • 11
  • 25

2 Answers2

51

This is a problem i used to have concerning URL redirects. Try the following code:

URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();

The "magic" here happens in these 2 steps:

ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));

By default InstanceFollowRedirects are set to true, but you want to set it to false to capture the second URL. To be able to get that second URL from the first URL, you need to get the header field called "Location".

Hakan Ozbay
  • 4,429
  • 2
  • 20
  • 28
  • Thank you for the answer, can you help adding authentication to url.openConnection()?. In the rest of my app I use HttpClient and execute() method passing the UsernamePasswordCredentials to pass auth. – sosergio Mar 09 '11 at 17:44
  • I'm afraid i'm not very familiar with httpClient and execute, but can show you a simple guide using the normal URL classes: http://blogs.deepal.org/2008/01/sending-basic-authentication-using-url.html – Hakan Ozbay Mar 12 '11 at 00:28
  • also consult: http://stackoverflow.com/questions/496651/connecting-to-remote-url-which-requires-authentication-using-java – Hakan Ozbay Mar 12 '11 at 00:31
  • @HakanOzbay +1 Works Perfect!! – Vipul Jan 16 '13 at 08:58
  • Is a try/catch necessary? That is what my Intelliji prompts me to do – Rohit Tigga Jun 06 '15 at 01:51
0

I have eliminated this issue on sites where we have a MikroTik router by using a Layer 7 protocol filter as shown below. This doesn't help the devices off the WiFi network (obviously) but at least gives them some reprieve when they are connected to home and/or work WiFi networks.

Firstly, create the protocol definition:

/ip firewall layer7-protocol
add comment="Frigging javascript redirects on chrome browsers" \
    name=Javascript_Redirect \
    regexp="^.+(spaces.slimspot.com|mostawesomeoffers.com).*\$"

Now, to actually filter this traffic out

/ip firewall filter
add action=drop chain=forward comment=\
    "Block and log Javascript_Redirect L7 Protocol" layer7-protocol=\
    Javascript_Redirect log=yes log-prefix=JSredirect_

Other firewalls that have Layer 7 filtering capacity could also block these redirects in a similar way.