If you want to detect some address or url are working, try the following code:
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:
Why we setConnectTimeout(5000) is avoid ANR of your device.
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
Why we setConnectTimeout(5000) is avoid ANR of your device.
沒有留言:
張貼留言