Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webservice availability check in android

What should be the factors considered while checking if webservice is available or running in android? FYI I am using HTTPGet object to send a request. I am currently checking only timeout exceptions.

Thanks..

PS Also checked android and ksoap, check web service availability but it doesn't seem to point me to a direction.

like image 471
nilMoBile Avatar asked Dec 03 '25 21:12

nilMoBile


2 Answers

public boolean isConnected()
{
    try{
        ConnectivityManager cm = (ConnectivityManager) getSystemService
                                                    (Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnected())
        {
            //Network is available but check if we can get access from the network.
            URL url = new URL("http://www.Google.com/");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(2000); // Timeout 2 seconds.
            urlc.connect();

            if (urlc.getResponseCode() == 200)  //Successful response.
            {
                return true;
            } 
            else 
            {
                 Log.d("NO INTERNET", "NO INTERNET");
                return false;
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return false;
}
like image 114
BobMcboberson Avatar answered Dec 06 '25 13:12

BobMcboberson


More faster way is using HttpGet request and DefaultHttpClient:

public boolean isConnected(String url)
{
      try
      {          
            HttpGet request = new HttpGet(url);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy()
            {
                  @Override
                  public long getKeepAliveDuration(HttpResponse response, HttpContext context)
                  {
                           return 0;
                  }
            });
            HttpResponse response = httpClient.execute(request);
            return response.getStatusLine().getStatusCode() == 200;

      }
      catch (IOException e){}
      return false;
}
like image 37
Nik Avatar answered Dec 06 '25 12:12

Nik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!