Question

I would like to have a second opinion on a small piece of Java code.

Will the method below always return an output string equal to the input string?

private static String func(final String url)
{
    HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
    con.setInstanceFollowRedirects(true);
    ...
    ...
    return con.getURL().toString();
}

The question refers to all possible scenarios, such as automatic redirection, etc.

Was it helpful?

Solution

If you look at URLConnection.getUrl() implementation, you can see that it returns the original URL passed to the constructor.

HttpURLConnection also doesn't change the original url.

To get the destination URL of a redirect you're supposed to call con.getHeaderField("Location"); - see for example: Retrieve the final location of a given URL in Java

So you get the original URL until you call connect() or some other method that results in establishing a connection.

If you set ((HttpURLConnection)con).setInstanceFollowRedirects(true); then after connect() if it really redirects you'll get the destination URL.

Redirect may not automatically happen for example when the protocol changes (e.g. http -> https).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top