Php Android检查远程服务器的可用性/检查远程服务器是否处于活动状态?
我正在构建一个android应用程序,它将输入参数作为IPADDRESS,我必须检查远程服务器是否可用 基本上,我是在努力达到目标Php Android检查远程服务器的可用性/检查远程服务器是否处于活动状态?,php,android,Php,Android,我正在构建一个android应用程序,它将输入参数作为IPADDRESS,我必须检查远程服务器是否可用 基本上,我是在努力达到目标 但是我想检查服务器是否处于活动状态,然后继续我的程序 您可以使用异步任务ping服务器并根据响应继续 使用类HttpURLConnection doInBackground(..) { boolean success = false; HttpURLConnection urlConnection; URL url = new URL("ht
但是我想检查服务器是否处于活动状态,然后继续我的程序 您可以使用异步任务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;
}
您可以在服务器上创建一个servlet/网页或任何您认为合适的内容,根据android的服务器状态返回ok或error。您必须调用该URL并检查返回值,还必须在try/catch上查看特定异常,例如与超时相关的异常,如果您的http请求返回200,那么还可以检查http状态,您可以从该URL检查获取服务器状态
如果url=”“或url=“”,上述代码仅给出
true
。如果我们有任何更改,比如“hp:”而不是“http”,它会抛出异常。如果“”表示可用,如果“”表示服务器不可用,我们如何找到结果。。。
`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