用Java如何判断链接是否有效
1个回答
展开全部
模拟HTTP提交,判断访问的HTTP STATUS CODE
仅供参考
package com.kidd.test.zhidao;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Hello world!
*
*/
public class Execute {
public static void main(String[] args) {
URL realUrl;
try {
realUrl = new URL("http://www.126.com");
} catch (MalformedURLException e) {
System.out.println("构造URL发生错误.");
return;
}
// 打开和URL之间的连接
HttpURLConnection connection;
int code ;
try {
connection = (HttpURLConnection) realUrl.openConnection();
connection.connect();
code = connection.getResponseCode() ;
} catch (IOException e) {
System.out.println("网络访问异常,可能是URL异常.");
return ;
}
if(code == 200){
System.out.println("URL可以正常访问.");
}else{
System.out.println("URL异常.HTTP STATUS CODE="+code);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询