java 判断一个url是否有效、可以访问的方法

时间:2025-03-10 10:56:18

有些时候,我们需要判断某个url是否可以访问,可以访问了,才允许继续进行,目前有两种方式,最后使用带超时时间的,
因为第一种超时时间不定,可能会出现阻塞的情况。

package ;
 
import ;
import ;
import ;
 
public class TestUrl {
 
    public static void main(String[] args) {
 
        testUrl("http://1.3.3.3/test");
        //最好使用下面这个,上面那个超时时间不定,所以可能会导致卡住的情况
        testUrlWithTimeOut("http://1.3.3.3", 2000);
    }
    
    public static void testUrl(String urlString){
        
        long lo = ();
        URL url;  
        try {  
             url = new URL(urlString);  
             InputStream in = ();  
             ("连接可用");  
        } catch (Exception e1) {  
             ("连接打不开!");  
             url = null;  
        }  
        
        (()-lo);
    }
    
    public static void testUrlWithTimeOut(String urlString,int timeOutMillSeconds){
        long lo = ();
        URL url;  
        try {  
             url = new URL(urlString);  
             URLConnection co =  ();
             (timeOutMillSeconds);
             ();
             ("连接可用");  
        } catch (Exception e1) {  
             ("连接打不开!");  
             url = null;  
        }  
        (()-lo);
    }
}


-----------------------------------

转载于:https://blog./u_4048786/3204505

相似篇:java 判断一个url是否有效、可以访问的方法_今人不见古时月,今月曾经照古人的博客-****博客 

相关文章