温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎样基于java或js获取URL返回状态码

发布时间:2021-02-02 11:28:27 来源:亿速云 阅读:397 作者:小新 栏目:编程语言

这篇文章主要介绍怎样基于java或js获取URL返回状态码,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

描述:使用java或者js访问某个网站,返回状态码

1.java实现

// 用getResponseCode可以获取URL返回状态码
String surl = "";
try {
      surl="你的url";
        URL url = new URL(surl);
        URLConnection rulConnection  = url.openConnection();
        HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
        httpUrlConnection.setConnectTimeout(300000);
        httpUrlConnection.setReadTimeout(300000);
        httpUrlConnection.connect();
        String code = new Integer(httpUrlConnection.getResponseCode()).toString();
        String message = httpUrlConnection.getResponseMessage();
        System.out.println("getResponseCode code ="+ code);
        System.out.println("getResponseMessage message ="+ message);
        if(!code.startsWith("2")){
          throw new Exception("ResponseCode is not begin with 2,code="+code);
        }
        System.out.println(getCurDateTime()+"连接"+surl+"正常");
     }catch(Exception ex){
        System.out.println(ex.getMessage());
     }

2.js实现(成功会返回200,如果页面找不到会返回404)

function GetHttpStatusCode($url){
  $curl = curl_init();
  curl_setopt($curl,CURLOPT_URL,$url);//获取内容url
  curl_setopt($curl,CURLOPT_HEADER,1);//获取http头信息
  curl_setopt($curl,CURLOPT_NOBODY,1);//不返回html的body信息
  curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//返回数据流,不直接输出
  curl_setopt($curl,CURLOPT_TIMEOUT,30); //超时时长,单位秒
  curl_exec($curl);
  $rtn= curl_getinfo($curl,CURLINFO_HTTP_CODE);
  curl_close($curl);
  return $rtn;
}
$url = "http://www.baidu.com";
GetHttpStatusCode($url);

以上是“怎样基于java或js获取URL返回状态码”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI