检测网页地址有效性java代码

时间:2023-03-08 21:00:26
package com.inspur.linkcheck;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; public class LinkCheck {
public static void main(String[] args) {
System.out.println(checkUrl("http://202.110.193.23:8000/zrqd/themes/default/skins/images/bg_body_footer.png"));
} public static boolean checkUrl(String url_s) {
try {
URL url = new URL(url_s);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
/**
* public int getResponseCode()throws IOException 从 HTTP 响应消息获取状态码。
* 例如,就以下状态行来说: HTTP/1.0 200 OK HTTP/1.0 401 Unauthorized 将分别返回 200
* 和 401。 如果无法从响应中识别任何代码(即响应不是有效的 HTTP),则返回 -1。
*
* 返回 HTTP 状态码或 -1
*/
int state = conn.getResponseCode();
System.out.println(state);
if (state == 200) {
return true;
} else {
System.out.println("invalid: " + url_s);
return false;
}
} catch (IOException e) {
return false;
}
} }