Skip to content

Instantly share code, notes, and snippets.

@valokafor
Created August 18, 2018 18:53
Show Gist options
  • Save valokafor/b8b02fbe5f3653cee570cac59f358700 to your computer and use it in GitHub Desktop.
Save valokafor/b8b02fbe5f3653cee570cac59f358700 to your computer and use it in GitHub Desktop.
Url Validator
/**
* Recursive method for resolving redirects. Resolves at most MAX_REDIRECTS times.
*
* @param url a URL
* @param remainingRedirects loop counter
* @return instance of URLConnection
* @throws IOException if connection fails
*/
protected boolean createConnection(URL url, int remainingRedirects) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
setConnectionProperties(connection);
int code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_MOVED_PERM ||
code == HttpURLConnection.HTTP_MOVED_TEMP ||
code == HttpURLConnection.HTTP_SEE_OTHER) {
if (remainingRedirects > 0) {
// Stop redirecting.
URL movedUrl = new URL(connection.getHeaderField("Location"));
if (!url.getProtocol().equals(movedUrl.getProtocol())) {
// HttpURLConnection doesn't handle redirects across schemes, so handle it manually, see
// http://code.google.com/p/android/issues/detail?id=41651
connection.disconnect();
return createConnection(movedUrl, --remainingRedirects); // Recursion
}
}
}
int code2 = connection.getResponseCode();
boolean result = code2 == 200;
connection.disconnect();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment