描述:使用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);