web服务-android中的web服务可用性检查



在检查web服务是否可用或在android中运行时,应该考虑哪些因素?仅供参考,我正在使用HTTPGet对象发送请求。我目前只检查超时异常。

谢谢。。

PS还检查了android和ksoap,检查了网络服务的可用性,但似乎没有给我指明方向。

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;
}

更快速的方法是使用HttpGet请求和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;
}

您可能应该检查HTTP状态代码

最新更新