Android HttpURLConnection: Handle HTTP redirects
15,570
Solution 1
Simply call getUrl()
on URLConnection
instance after calling getInputStream()
:
URLConnection con = new URL(url).openConnection();
System.out.println("Orignal URL: " + con.getURL());
con.connect();
System.out.println("Connected URL: " + con.getURL());
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();
If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:
HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);
Solution 2
private HttpURLConnection openConnection(String url) throws IOException {
HttpURLConnection connection;
boolean redirected;
do {
connection = (HttpURLConnection) new URL(url).openConnection();
int code = connection.getResponseCode();
redirected = code == HTTP_MOVED_PERM || code == HTTP_MOVED_TEMP || code == HTTP_SEE_OTHER;
if (redirected) {
url = connection.getHeaderField("Location");
connection.disconnect();
}
} while (redirected);
return connection;
}
Comments
-
Julian almost 2 years
I'm using
HttpURLConnection
to retrieve an URL just like that:URL url = new URL(address); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); // ...
I now want to find out if there was a redirect and if it was a permanent (301) or temporary (302) one in order to update the URL in the database in the first case but not in the second one.
Is this possible while still using the redirect handling of
HttpURLConnection
and if, how? -
Julian about 11 yearsWith your first code example, is there any way to distinguish between a temporary and a permanent redirect? And your second example leaves the actual redirect handling up to me which I'd like to avoid.
-
syb0rg about 11 yearsThere probably is a way to get all the temporary redirects, but I'm not sure how to go about this.
-
Keab42 almost 10 yearsTemporary redirects and Permanent redirects should have different response codes. 301 = Permanent. 302 and sometimes 307 are Temporary.
-
Shajeel Afzal over 7 yearsHow to know where the whether redirection happened after getting its content? Is there any way?
-
Admin about 6 yearsI would suggest adding a maximum to the loop
-
danik about 6 yearsAgreed with you.
-
Jaks Blackhat almost 2 yearswhat means a maximum?