zoukankan      html  css  js  c++  java
  • 用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);
  • 相关阅读:
    柔性数组
    2015阿里秋招当中一个算法题(经典)
    LAMP环境搭建
    JS和JQuery中的事件托付 学习笔记
    #17 Letter Combinations of a Phone Number
    码农生涯杂记_5
    【C++ Primer每日刷】之三 标准库 string 类型
    扎根本地连接未来 千米网的电商“红海”生存术
    poj 3356
    经验之谈—OAuth授权流程图
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/11576438.html
Copyright © 2011-2022 走看看