Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get response header location using Java's URLConnection

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

like image 305
Yaniv Golan Avatar asked Sep 24 '10 10:09

Yaniv Golan


1 Answers

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

like image 108
axtavt Avatar answered Sep 18 '22 18:09

axtavt