我知道您尝试 ping 服务器并得到 200 的响应代码,这是正常的情况,但是当您得到 200 的响应时,这可能取决于各种因素。
Reference:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
现在,我相信如果data packets 被发送回服务器,并且如果您确实在响应中收到数据包,则连接成功。
但是,您可能希望等待服务器响应或设置一些connection 或read timeout 以确保没有错误响应。
这是我过去用来确定互联网连接的示例代码。我正在使用Process 来确定检查并尝试将返回值设为0。
public Boolean isConnectionAvailable() {
try {
Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = process.waitFor();
boolean reachable = (returnVal == 0);
if (reachable) {
Log.i(TAG, "Connection Successful");
return reachable;
} else {
Log.e(TAG, "No Internet access");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
process.destroy();
}
return false;
}
在上面的代码中,我有谷歌服务器作为检查的媒介。但是,您也可以像这样使用 8.8.8.8:
Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 8.8.8.8");
进程执行时,会给出一个返回值,这将决定连接的失败和成功。
关键元素是使用来自causes the calling thread to wait for the native process associated with this object to finish executing. 的java 类Process.class 中的waitFor() 方法。
参考:http://developer.android.com/reference/java/lang/Process.html#waitFor%28%29
试一试,如果有帮助,我会很高兴。如果有更好的答案,我很高兴接受它.. 谢谢.. :)