Java判断一个url是否访问

最近遇到一个视频链接打开404的情况下,导致终端app直接卡死,

规避的方法是:判断视频url是否可用,可用的话在继续操作,不可用直接跳过

public class UrlUtils {
    public static void testUrl(String urlString){

        long lo = System.currentTimeMillis();
        URL url;
        try {
            url = new URL(urlString);
            InputStream in = url.openStream();
            System.out.println("连接可用");
        } catch (Exception e1) {
            System.out.println("连接打不开!");
            url = null;
        }

        System.out.println(System.currentTimeMillis()-lo);
    }

    public static boolean  testUrlWithTimeOut(String urlString,int timeOutMillSeconds){
        long lo = System.currentTimeMillis();
        URL url;
        try {
            url = new URL(urlString);
            URLConnection co =  url.openConnection();
            co.setConnectTimeout(timeOutMillSeconds);
            co.connect();
            System.out.println("连接可用");
            return true;
        } catch (Exception e1) {
            System.out.println("连接打不开!");
            url = null;
            return false;
        }
//        System.out.println(System.currentTimeMillis()-lo);
    }


}

第一种方法会出现时间不确定,造成堵塞的情况,so用第二种有超时时间的

使用方法:

UrlUtils.testUrlWithTimeOut(data.getPro_Info().get(0).get视频地址(),2000)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值