测试通过,对Url异常都做了简单的捕获。
package src;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class ConnTestUtil {
public static boolean getContent(String ip) {
return getContent(ip, 3000);
}
public static boolean getContent(String ip, int timeout) {
URL url = null;
URLConnection conn = null;
BufferedReader in = null;
try {
url = new URL("http://" + ip);
conn = url.openConnection();
conn.setConnectTimeout(timeout);
in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
if ((in.readLine()) != null) {
in.close();
System.out.println(ip + "--连接成功");
return true;
} else {
in.close();
return false;
}
} catch (MalformedURLException e) {
System.err.println(ip + "--URL转化异常");
return false;
} catch (IOException e) {
System.err.println(ip + "--连接失败");
return false;
} finally {
conn = null;
url = null;
}
}
public static void main(String args[]) {
System.out.println(getContent("192.168.1.153"));
// System.out.println(getContent("www.baidu.com"));
// System.out.println(12 % 20);
}
}