方法一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
try { URL url = new URL(address); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setUseCaches( false ); conn.setInstanceFollowRedirects( true ); conn.setConnectTimeout(waitMilliSecond); conn.setReadTimeout(waitMilliSecond); //HTTP connect try { conn.connect(); } catch (Exception e) { e.printStackTrace(); return false ; } int code = conn.getResponseCode(); if ((code >= 100) && (code < 400)){ return true ; } return false ; } catch (Exception e){ e.printStackTrace(); return false ; } |
方法二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
try { URL url = new URL(address); String host = url.getHost(); int port = url.getPort(); if (port == -1) { port = 80; } Socket socket = new Socket(); InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port); socket.connect(isa, timeout); if (socket.isConnected()) { return true ; } else { return false ; } } catch (Exception e) { e.printStackTrace(); } finally { if (socket != null ) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } |
以上这篇Android检测url地址是否可达的两种方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Q1009355422/article/details/56672650