您的位置:首页 > 运维架构 > 网站架构

在java 中判断网站正确打开

2008-11-26 17:36 134 查看
这里是程序片断,

try{
URL url = new URL("http://www.mocoto.com/");
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
httpConnection.getURL();
int responseCode=httpConnection.getResponseCode();
String ResponseMessage=httpConnection.getResponseMessage();
System.out.println("^X^"+x+"/t"+httpConnection.getURL());
System.out.println("^X^"+x+"/t"+responseCode);
System.out.println("^X^"+x+"/t"+ResponseMessage);
}
catch(Exception e){}
-----------------------------
System.out.println("^X^"+x+"/t"+ResponseMessage);

输出为 ok ,就是连上了。对了,上面的程序中变量x是我循环时用的,你可以去掉

其中
int responseCode = httpConnection.getResponseCode();
这个方法返回了 一个 ResponseCode 值
这是一个 http 协议的 连接返回值 其中 200 表示正常连接
其他的 如 400 401 403 404 等等 都表示连接出了问题
每个 三位数表示一种错误 详情以去查 http 协议的规范

所以 基本上 只要判断 这个 ResponseCode 是否为 200 就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: