如果你想要測試某個網址是否可以正常的連線,你可以使用:
int count = 0;
while (count < 5) {
try {
URL myUrl = new URL("http://www.google.com");
HttpURLConnection myConnection =
(HttpURLConnection) myUrl.openConnection();
myConnection.setConnectTimeout(5000);
int state = myConnection.getResponseCode();
if (state == 200) {
Log.d("gill","the address is available!");
}
break;
} catch (Exception ex) {
count = count + 1;
}
Log.d("gill","the address is unavailable!");
}
getResponseCode() will return:
200 : connect normally
404 : can't connect
-1 : can't detect the result
設定setConnectTimeout(5000)表示連線5秒還沒成功就放棄。
沒有留言:
張貼留言