12

can someone kindly suggest what I'm doing wrong here?
I'm trying to get the header location for a certain URL using Java here is my code:

URLConnection conn = url.openConnection();
String location = conn.getHeaderField("Location");  

it's strange since I know for sure the URL i'm refering to return a Location header and using methods like getContentType() or getContentLength() works perfectly

buræquete
  • 14,226
  • 4
  • 44
  • 89
Yaniv Golan
  • 982
  • 5
  • 15
  • 28

2 Answers2

18

Perhaps Location header is returned as a part of redirect response. If so, URLConnection handles redirect automatically by issuing the second request to the pointed resource, so you need to disable it:

((HttpURLConnection) conn).setInstanceFollowRedirects(false);

EDIT: If you actually need a URL of the redirect target and don't want to disable redirect handling, you may call getURL() instead (after connection is established).

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • it works in most cases. However, it does not work for this url: https://db.tt/4do5q7Tk. However, you do are able to see the header from this online too: http://www.srccodes.com/tools/html/http-headers-viewer – LiangWang Nov 02 '16 at 03:07
0

Just a follow up to axtavt's answer... If the url has multiple redirects, you could do something like this in order to obtain the direct link:

String location = "http://www.example.com/download.php?getFile=1";
HttpURLConnection connection = null;
for (;;) {
    URL url = new URL(location);
    connection = (HttpURLConnection) url.openConnection();
    connection.setInstanceFollowRedirects(false);
    String redirectLocation = connection.getHeaderField("Location");
    if (redirectLocation == null) break;
    location = redirectLocation;
}
Community
  • 1
  • 1
tingo
  • 31
  • 3