masterpeter2720 masterpeter2720 - 1 year ago 53
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:

it moves to

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();
urlStatusCode = connection.getResponseCode();

} catch (IOException e) {
// other error types to be reported
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 Source

You can get the new URL with

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