Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java, android, resolve an url, get redirected uri

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.

like image 447
sosergio Avatar asked Mar 05 '11 15:03

sosergio


People also ask

How do I redirect a URL to another URL in Java?

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request.

What is redirect URI in Android?

The redirect uri is where the client will get send to after the account authorization is successful. You could also set up a redirect for an authorization failure.

What causes URL redirection?

Web pages may be redirected to a new domain for three reasons: a site might desire, or need, to change its domain name; an author might move their individual pages to a new domain; two web sites might merge.


1 Answers

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".

like image 100
Hakan Ozbay Avatar answered Sep 24 '22 03:09

Hakan Ozbay