TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
对于一个链接的有效性,一般我们能想到的最有效的方法便是用鼠标点击一下,看看能不能打开,如果不行,则说明这个链接是无效的,当然对一个或十个链接我们还有耐心去一个个的点击,但是对多批量的链接呢?要怎么做呢?这里给大家介绍一种好的方法,用java就可以轻易做到!不信你可以试试哦,例子很简单!
- 一、
- /**
- * 判断链接是否有效
- * 输入链接
- * 返回true或者false
- */
- public static boolean isValid(String strLink) {
- URL url;
- try {
- url = new URL(strLink);
- HttpURLConnection connt = (HttpURLConnection)url.openConnection();
- connt.setRequestMethod("HEAD");
- String strMessage = connt.getResponseMessage();
- if (strMessage.compareTo("Not Found") == 0) {
- return false;
- }
- connt.disconnect();
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- 二、
- package test;
- import java.net.*;
-
- public class riqi {
- public static void main(String[] args) {
- try {
- URL url=new URL( "http://www.dukai168.cn");
- URLConnection conn=url.openConnection();
- String str=conn.getHeaderField(0);
- if (str.indexOf( "OK ")> 0)
- {
- System.out.println( "正常! ");
- }else{
- System.out.println( "不能游览 ");
- }
- } catch (Exception ex) {
- }
复制代码 |
|