欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android检测url地址是否可达的两种方法

程序员文章站 2022-06-23 14:57:20
方法一 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地址是否可达的两种方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。