masterpeter2720 masterpeter2720 - 3 months ago 11
Java Question

Getting new Url if Moved Permanently

I am developing a code for a project where a part of the code is to check a list of Urls (Web site) is live and and confirm it.

So far every thing is working as planned, expect some pages that are Moved Permanently with error 301 regarding this list. In case of error 301 I need to get the new Url info and pass it in a method before returning true.

The following example is just move to https but other examples could be moved to another Url, so if you call this site:

http://en.wikipedia.org/wiki/HTTP_301


it moves to

https://en.wikipedia.org/wiki/HTTP_301


Which is fine, I just need to get the new Url.

Is this possible and how?

This is my working code part so far:

boolean isUrlOk(String urlInput) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlInput);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
urlStatusCode = connection.getResponseCode();

} catch (IOException e) {
// other error types to be reported
e.printStackTrace();
}
if (urlStatusCode == 200) {
return true;
} else if (urlStatusCode == 301) {
// call a method with the correct url name
// before returning true
return true;
}
return false;
}

Answer

You can get the new URL with

String newUrl = connection.getHeaderField("Location");