如何检查服务器连接是否存在?

时间:2016-02-21 11:07:11

标签: java android android-asynctask server

在我的应用程序中,我有asyncTask类,它连接到本地/远程服务器以获取一些数据,我想在asyncTask运行之前检查服务器连接, 我有这个功能:

public static boolean checkServerAvailable(String hostURL) {
    HttpURLConnection connection = null;
    try {
        URL u = new URL(hostURL);
        connection = (HttpURLConnection) u.openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();
        System.out.println("" + code);
        return true;
        // You can determine on HTTP return code received. 200 is success.
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

此函数使用超时连接到服务器,如果超时到期,则表示没有服务器。问题是,我运行此代码并且它已经返回"没有服务器"即使服务器存在。

我试图像5000毫秒那样设置一个大的超时时间,但它会暂停UI很长时间,有时仍会返回"没有服务器"即使服务器存在。

我该怎么办? 谢谢!

2 个答案:

答案 0 :(得分:0)

  

在asyncTask运行之前检查服务器连接

然后你必须在另一个AsyncTask中执行此操作。

所以这一切都没有意义。

你没有使用StrictMode是吗?

答案 1 :(得分:-1)

尝试使用socket这里是示例代码

    Socket socket;
    final String host = "your.server.IP.or.host";
    final int port = 80;
    final int timeout = 5000;   // 5 seconds or what ever time you want 

    try {
      socket = new Socket();
      socket.connect(new InetSocketAddress(host, port), timeout);
    }
    catch (UnknownHostException uhe) {
      Log.e("ServerSock", "I couldn't resolve the host you've provided!");
    }
    catch (SocketTimeoutException ste) {
      Log.e("ServerSock", "After a reasonable amount of time, I'm not able to connect, Server is probably down!");
    }
    catch (IOException ioe) {
      Log.e("ServerSock", "Hmmm... Sudden disconnection, probably you should start again!");
    }