gpt4 book ai didi

java - 如何检查url是否可达

转载 作者:行者123 更新时间:2023-12-01 06:22:34 25 4
gpt4 key购买 nike

我正在尝试检查服务器 url 在 android 中是否可达。我想检查的网址如下:https://mydomain.se:8081/,也可以通过互联网访问。但遇到问题,因为下面的方法有时返回 true,有时返回 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;
}

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

最佳答案

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

关于java - 如何检查url是否可达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42813528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com