Android检查远程服务器的可用性/检查远程服务器是否存活?

时间:2011-11-15 01:05:27

标签: php android

我正在构建一个android应用程序,它将输入参数作为IPADDRESS,我必须检查远程服务器是否可用?

基本上我想尝试http://serverip/request.php

但我想检查服务器是否处于活动状态,然后继续我的程序。

2 个答案:

答案 0 :(得分:0)

您可以使用AsyncTask来ping服务器并根据响应进行操作。

使用HttpURLConnection类

doInBackground(..) {
    boolean success = false;
    HttpURLConnection urlConnection;
    URL url = new URL("http://www.android.com/");
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
    }catch(Exception e){
        Log.e(TAG,"OpenConnection call failed");
    }
        success = true;
    }
    return success;
}

答案 1 :(得分:0)

您可以在服务器上创建一个servlet /网页或任何您觉得舒服的东西,具体取决于您的Android服务器状态,您必须调用该URL并检查返回值,同样在您的try / catch上您必须注意特定的例如,与超时相关的异常,如果您的http请求返回200则检查http状态然后是可以的,您可以从该URL获取服务器状态检查http://developer.android.com/reference/java/net/HttpURLConnection.html

        `boolean isOK = false;
        try {
            URL url = new URL("http://yourserverurl/yourstatusmethod");
            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            urlcon.connect();
            if (urlcon.getResponseCode() == 200) {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    String serverStatus = readStream(in); //assuming that "http://yourserverurl/yourstatusmethod" returns OK or ERROR depending on your server status check         
                    isOK = (serverStatus.equalsIgnoreCase("OK"));
            }else{
              isOK = false;
            }

            url.disconnect();

        } catch (MalformedURLException e1) {
                    isOK = false;
                    e1.printStackTrace();
        } catch (IOException e) {
                    isOK = false;
                    e.printStackTrace();
        }

    the readStream is a method that convert inputstream to string
    `public static String readStream (InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }    return out.toString();
    }`

this is just and idea.... there are a lot of ways to check server availability