我能够使用Socket类完成此操作。但是我希望得到HttpUrlConnection提供的内容。
现在我正在做以下事情:
public void checkServerStatus(String IP_ADDRESS, int PORT, String SERVER_NAME) {
try(Socket s = new Socket(IP_ADDRESS, PORT)) {
System.out.println("Connection good on "+SERVER_NAME);
} catch (IOException ex) {
System.out.println("There was an IO error "+ ex);
}catch(SecurityException ex) {
System.out.println("There was an security error "+ ex);
} catch (IllegalArgumentException ex){
System.out.println("There was an IllegalArgumentException "+ ex);
}
}
但是我想做点什么:
public static String getStatus(String url) throws IOException {
String result = "";
try {
URL siteURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == 200) {
result = "Green";
}
} catch (Exception e) {
result = "->Red<-";
}
return result;
}
但是只有IP地址和我要检查的端口。
阅读URL API后,我无法做到这一点,HttpUrlConnection依赖于URL。
我正在尝试创建服务器运行状况类型的程序,如果出现问题则返回代码。