87 lines
2.1 KiB
Java
87 lines
2.1 KiB
Java
|
|
package com.zhgd.xmgl.util;
|
||
|
|
|
||
|
|
import org.apache.commons.lang3.StringUtils;
|
||
|
|
import org.slf4j.Logger;
|
||
|
|
import org.slf4j.LoggerFactory;
|
||
|
|
|
||
|
|
import java.io.IOException;
|
||
|
|
import java.net.HttpURLConnection;
|
||
|
|
import java.net.InetAddress;
|
||
|
|
import java.net.URL;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Ping服务器IP的工具
|
||
|
|
*
|
||
|
|
* @author leo
|
||
|
|
*/
|
||
|
|
public class PingUtil {
|
||
|
|
private static final Logger LOGGER = LoggerFactory.getLogger(PingUtil.class);
|
||
|
|
|
||
|
|
// 默认超时时间为10秒
|
||
|
|
private static final int DEFAULT_TIMEOUT = 5000;
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Ping一个地址
|
||
|
|
*
|
||
|
|
* @param ip Ping的IP
|
||
|
|
* @param timeout 超时时间
|
||
|
|
* @return
|
||
|
|
*/
|
||
|
|
public static boolean ping(String ip, int timeout) {
|
||
|
|
boolean status = false;
|
||
|
|
try {
|
||
|
|
status = InetAddress.getByName(ip).isReachable(timeout);
|
||
|
|
} catch (IOException e) {
|
||
|
|
LOGGER.warn(e.getMessage());
|
||
|
|
}
|
||
|
|
return status;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 使用默认超时Ping一个地址
|
||
|
|
*
|
||
|
|
* @param ip Ping的IP
|
||
|
|
* @return
|
||
|
|
*/
|
||
|
|
public static boolean ping(String ip) {
|
||
|
|
return ping(ip, DEFAULT_TIMEOUT);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Ping一个HTTP地址
|
||
|
|
*
|
||
|
|
* @param url
|
||
|
|
* @param timeout
|
||
|
|
* @return
|
||
|
|
*/
|
||
|
|
public static boolean pingUrl(String url, int timeout) {
|
||
|
|
boolean status = false;
|
||
|
|
try {
|
||
|
|
if (StringUtils.isNotEmpty(url)) {
|
||
|
|
URL urlObj = new URL(url);
|
||
|
|
HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
|
||
|
|
oc.setUseCaches(false);
|
||
|
|
oc.setConnectTimeout(DEFAULT_TIMEOUT);
|
||
|
|
status = oc.getResponseCode() == 200;
|
||
|
|
}
|
||
|
|
} catch (IOException e) {
|
||
|
|
LOGGER.warn(e.getMessage());
|
||
|
|
}
|
||
|
|
return status;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static boolean pingUrl(String url) {
|
||
|
|
return pingUrl(url, DEFAULT_TIMEOUT);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static void main(String[] args) throws IOException {
|
||
|
|
String url = "http://182.101.141.23:83/openUrl/M4XmCic/live.m3u8";
|
||
|
|
boolean status = pingUrl(url);
|
||
|
|
if (status) {
|
||
|
|
System.out.println("OK");
|
||
|
|
} else {
|
||
|
|
System.out.println("Fail");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|