2

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.

barak manos
  • 29,648
  • 10
  • 62
  • 114

1 Answers1

2

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

Community
  • 1
  • 1
Jakub Kotowski
  • 7,411
  • 29
  • 38
  • are you sure? what if I call con.setInstanceFollowRedirects(true)? – barak manos Jan 01 '14 at 17:59
  • in that case, before you call connect() or some other method that causes a connect you'll get the original URL. After connect() with follow redirects true you'll get the destination URL if it really followed the redirect (it won't for example if the protocol changes: http -> https). – Jakub Kotowski Jan 01 '14 at 18:14
  • So basically, what you're saying here means that the answer above is incorrect, right? – barak manos Jan 01 '14 at 18:16
  • yes, added the other case too now. Btw, it's difficult to verify because HttpURLConnection is just an abstract class and I guess the actual implementation is platform dependent... so the exact behavior may actually be different on different platforms... – Jakub Kotowski Jan 01 '14 at 18:19