Android检测url地址是否可达的两种方法
程序员文章站
2022-03-23 13:38:49
方法一
try{
url url = new url(address);
httpurlconnection conn = (httpurlconne...
方法一
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; }
方法二
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地址是否可达的两种方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。