Java检测网络是否连通检查ip、URL和API接口
Java检测网络是否连通检查ip、URL和API接口
·
一、检测ip是否连通
/**
* 检测IP地址是否能ping通
*
* @param ip IP地址
* @param timeout 检测超时(毫秒)
* @return 是否ping通
*/
public static boolean ping(String ip, int timeout) {
try {
return InetAddress.getByName(ip).isReachable(timeout); // 当返回值是true时,说明host是可用的,false则不可。
} catch (Exception ex) {
return false;
}
}
二、检测一个网页URL是否连通
/**
* 检测URL是否能连通
*
* @param urlStirng
* @return
*/
public static boolean checkUrl(String urlStirng) {
try {
URL url = new java.net.URL(urlStirng);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0");
connection.setRequestMethod("GET");
// 设置单次请求是否支持重定向,默认为 setFollowRedirects 方法设置的值
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(500);
connection.connect();
System.out.println(connection.getResponseCode());
if (connection.getResponseCode() == 200) {//判断状态码
String htmlCode = "";
InputStream in = connection.getInputStream();
byte[] buffer = new byte[500];
in.read(buffer);
htmlCode = new String(buffer);
if (htmlCode.contains("错误页") || htmlCode.contains("{\"message\":\"请求的URI地")) {//拿到返回内容判断是否返回的是错误页
return false;
}
} else {
return false;
}
} catch (IOException e) {
return false;
}
return true;
}
三、检测API接口是否连通
- 只能通过状态码是否为404判断,如果网络不通则会连接失败到 catch 中返回false
/**
* 检测API是否能连通
*
* @param urlStirng
* @return
*/
public static boolean checkUrl(String urlStirng) {
try {
URL url = new java.net.URL(urlStirng);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0");
connection.setRequestMethod("GET");
// 设置单次请求是否支持重定向,默认为 setFollowRedirects 方法设置的值
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(500);
connection.connect();
System.out.println(connection.getResponseCode());
if (connection.getResponseCode() != 404) {//判断状态码
return true;
} else {
return false;
}
} catch (IOException e) {
return false;
}
}
- 请求方式必须全部字母大写,比如POST请求,不能写成post请求
- 如果请求方式错误,并不会连接失败,而是请求码得到的为405错误。但是得到的是405状态码非200状态码,可以显示连通。
其他
需要使用的maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
参考文档
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)