我正在尝试通过以下代码检查主机的可访问性:
Socket socket = new Socket();
try
{
SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName("https://www.google.co.in"), 80);
socket.connect(socketAddress, 2000);
}
catch (IOException e)
{
Log.e("server",e.getMessage());
return false;
}
finally
{
if (socket.isConnected()) {
try {
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
但它总是返回false。还有什么需要补充的。 它提供了未解析的主机URL异常。
答案 0 :(得分:0)
请改为尝试:
public static boolean ping(String url, int timeout) {
url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
return (200 <= responseCode && responseCode <= 399);
} catch (IOException exception) {
return false;
}
}
有了这个你正在ping一个网站,比如谷歌,所以你可以检查可达性。