misszeze 0 Newbie Poster

hello Java programmers

I need a method to check links to validate them if they were valid or broken, so far i found two methods at the internet:
1- the first one code:

HttpURLConnection urlConnection = null;
try{
URL url = new URL(link);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
String redirectLink = urlConnection.getHeaderField("Location");
if (redirectLink != null && !url.equals(redirectLink)) {
return isLive(redirectLink);
} else {
return urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK;
}
}catch (Exception e) {
return false;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}

I understood the code util the piece of it marked in red if anybody understood it especially the next part of the if condition

url.equals(redirectLink)

please help me.
2- the next code is:

int code=0;
    
    try{
        URL url = new URL("http://easywayserver.com/");

        HttpURLConnection link=(HttpURLConnection)url.openConnection();
        code=link.getResponseCode();
    }
    catch(BindException e)
    {
        code=1;
        e.printStackTrace();
    }
    catch(ConnectException e)
    {
        code=2;
        e.printStackTrace();
    }
    catch(HttpRetryException e)
    {
        code=3;
        e.printStackTrace();
    }
    catch(MalformedURLException e)
    {
        code=4;
        e.printStackTrace();
    }

it is very brief and simple but i was asking why he used the link.getResponseCode(); before connecting like the one in the first code i think we must use the connect method to establish the connection before getting the response

, and is the second code better than the first one please help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.