Skip to content

Commit

Permalink
improve the redirection of urls
Browse files Browse the repository at this point in the history
  • Loading branch information
carlosuc3m committed Jul 5, 2023
1 parent 8780ba2 commit 29f482a
Showing 1 changed file with 45 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
Expand Down Expand Up @@ -495,10 +496,10 @@ public static long getFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == 302)
return getFileSize(new URL(conn.getHeaderField("Location")));
if (conn.getResponseCode() > 300 && conn.getResponseCode() < 304)
return getFileSize(redirectedURL(url, conn));
if (conn.getResponseCode() != 200)
throw new Exception();
throw new Exception("Unable to connect to: " + url.toString());
return conn.getContentLengthLong();
} catch (IOException e) {
throw new RuntimeException(e);
Expand All @@ -510,6 +511,47 @@ public static long getFileSize(URL url) {
}
}

/**
* This method shuold be used when we get the following response codes from
* a {@link HttpURLConnection}:
* - {@link HttpURLConnection#HTTP_MOVED_TEMP}
* - {@link HttpURLConnection#HTTP_MOVED_PERM}
* - {@link HttpURLConnection#HTTP_SEE_OTHER}
*
* If that is not the response code or the connection does not work, the url
* returned will be the same as the provided.
* If the method is used corretly, it will return the URL to which the original URL
* has been redirected
* @param url
* original url. Connecting to that url must give a 301, 302 or 303 response code
* @param conn
* connection to the url
* @return the redirected url
*/
public static URL redirectedURL(URL url, HttpURLConnection conn) {
int statusCode;
try {
statusCode = conn.getResponseCode();
} catch (IOException ex) {
return url;
}
if (statusCode != HttpURLConnection.HTTP_MOVED_TEMP
&& statusCode != HttpURLConnection.HTTP_MOVED_PERM
&& statusCode != HttpURLConnection.HTTP_SEE_OTHER)
return url;
String newURL = conn.getHeaderField("Location");
try {
return new URL(newURL);
} catch (MalformedURLException ex) {
}
try {
String mainDomain = url.toURI().getHost();
return new URL(mainDomain + newURL);
} catch (URISyntaxException | MalformedURLException e) {
return null;
}
}

/**
* REtrieve a formated string containing each of the files that have been
* downloaded
Expand Down

0 comments on commit 29f482a

Please sign in to comment.