如何检查URL是否可访问

时间:2017-03-15 15:04:22

标签: java android httpurlconnection

我正在尝试检查服务器url是否可以在android中访问。 我要检查的网址是这样的:https://mydomain.se:8081/,也可以从互联网上访问。但是在某个时候,方法返回true并且有时间错误时会出现问题。

  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;
}

还有其他方法可以通过移动数据从Android检查服务器吗?

1 个答案:

答案 0 :(得分:-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;
}