1

I am trying to check server url is reachable or not in android. url which i want to check is like this: https://mydomain.se:8081/ and also reachable from internet. But getting a problem as sometime below method return true and some time false.

  public boolean isBackendAccessAble(String serverUrl) {
    String host = serverUrl.substring(serverUrl.indexOf("://") + 3, serverUrl.lastIndexOf(":"));
    int port = Integer.parseInt(serverUrl.substring(serverUrl.lastIndexOf(":") + 1, serverUrl.length() - 1));
    boolean isReachable = false;
    try {
        SocketAddress sockAddress = new InetSocketAddress(host, port);
        Socket sock = new Socket();
        int timeoutMs = 2000; // 2 seconds
        sock.connect(sockAddress, timeoutMs);
        isReachable = true;
    } catch (Exception e) {
        Log.w(TAG, "Unable to check serverUrl:" +   serverUrl);
    }
    return isReachable;
}

is there any other alternative to check the server from android over mobile data?

  • Yes offcourse mobile have. even i can browse the backend url from phone browser. –  Mar 15 '17 at 15:08
  • So, your methond returns true or false even with internet connection ? – AMB Mar 15 '17 at 15:09
  • Yes. sometime it return me true and some time return false. –  Mar 15 '17 at 15:10
  • Take a look at this http://stackoverflow.com/questions/25805580/how-to-quickly-check-if-url-server-is-available – AMB Mar 15 '17 at 15:11

1 Answers1

-2
 public boolean isBackendAccessAble(String serverUrl) {
    String host = serverUrl.substring(serverUrl.indexOf("://") + 3, serverUrl.lastIndexOf(":"));
    int port = Integer.parseInt(serverUrl.substring(serverUrl.lastIndexOf(":") + 1, serverUrl.length() - 1));
    boolean isReachable = false;
    try {
        SocketAddress sockAddress = new InetSocketAddress(host, port);
        Socket sock = new Socket();
        int timeoutMs = 2000; // 2 seconds
        sock.connect(sockAddress, timeoutMs);
        isReachable = true;
    } catch (Exception e) {
        Log.w(TAG, "Unable to check serverUrl:" +   serverUrl);
 if (e instanceof SocketTimeoutException ){
   //the url is not reachable
isReachable=false;
 }
    }
    return isReachable;
}
Daniel Raouf
  • 2,307
  • 1
  • 22
  • 28
  • i find a problem. this is because of calling this method from a main thread so it is given me exception sometime: android.os.NetworkOnMainThreadException. Can someone give me hint if i use new thread and use this connection stuff with run, how i can add wait until started thread finish and give response back ? –  Mar 15 '17 at 15:25