web服务可用性检查android

时间:2011-06-28 13:52:48

标签: android web-services

检查webservice是否可用或在android中运行时应考虑的因素是什么?仅供参考我正在使用HTTPGet对象发送请求。我目前只检查超时异常。

谢谢..

PS还检查了android and ksoap, check web service availability,但它似乎没有指向我的方向。

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

更快捷的方法是使用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;
}

答案 2 :(得分:0)

您应该查看HTTP Status Codes