Check if website is available

160 views Asked by At

I want to check if website is available. It works when website is available, but it crash everytime when you can't connect to the website. If there is problem with NetTask class.

    String netAddress = null;
    try
    {
        netAddress = new NetTask().execute("www.googlasdasdde.com").get();
        if(netAddress == null || netAddress == "" || netAddress.isEmpty()){
            Log.d("111", "brak sieci");
        } else {
            Log.d("111", "server działa");

        }
    }
    catch (Exception e1)
    {
        e1.printStackTrace();
    }

And NetTask:

public class NetTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... params)
    {
        java.net.InetAddress addr = null;
        try {
            addr = java.net.InetAddress.getByName(params[0]);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return addr.getHostAddress();
    }
}
3

There are 3 answers

0
Stultuske On BEST ANSWER
public class NetTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... params)
    {
        java.net.InetAddress addr = null;
        try {
            addr = java.net.InetAddress.getByName(params[0]);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return addr.getHostAddress();
    }
}

Here, if you can't connect, the Exception is thrown, and you print the stacktrace.

Right after that, you try to return the hostAddress member of addr, but addr is null in this case.

either add a return statement in the try block, and return null after the try catch (or in the catch block), or throw an Exception in the catch block.

0
Randyka Yudhistira On

If addr is null then you cannot get the address using .getHostAddress(). Just return it as null.

public class NetTask extends AsyncTask<String, Integer, String>
{
    @Override
    protected String doInBackground(String... params)
    {
        java.net.InetAddress addr = null;
        try {
            addr = java.net.InetAddress.getByName(params[0]);
            return addr.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }
}
0
anx On

From the Documentation:

public static InetAddress getByName(String host)
                          throws UnknownHostException

This means that it is actually normal beahviour for the function to throw an Exception, (or crash if not caught) in case the hostname does not exist.

So just stick to throw-catch with one modification, like this:

java.net.InetAddress addr = null;
try {
    addr = java.net.InetAddress.getByName(params[0]);
    return addr.getHostAddress();
} catch (UnknownHostException e) {
    return null; }

This should either return an Address OR NULL.