SoFunction
Updated on 2025-03-01

Two ways to detect whether the URL is reachable on Android

Method 1

try{
  URL url = new URL(address);
  HttpURLConnection conn = (HttpURLConnection)();
  (false);
  (true);
  (waitMilliSecond);
  (waitMilliSecond);

  //HTTP connect
  try {
    ();
  } catch(Exception e) {
    ();
    return false;
  }

  int code = ();
  if ((code >= 100) && (code < 400)){
    return true;
  }

  return false;
}catch (Exception e){
  ();
  return false;
}

Method 2

try {
  URL url = new URL(address);
  String host = ();
  int port = ();
  if (port == -1) {
    port = 80;
  }
  Socket socket = new Socket();
  InetSocketAddress isa = new InetSocketAddress((host), port);

  (isa, timeout);
  if (()) {
    return true;
  } else {
    return false;
  }
} catch (Exception e) {
  ();
} finally {
  if (socket != null) {
    try {
      ();
    } catch (IOException e) {
      ();
    }
  }
}

The two methods of detecting whether the URL address is reachable in the above article are all the contents I share with you. I hope you can give you a reference and I hope you can support me more.