下面代码看下java判断http地址是否连通

private boolean isOk(String url) {
        if(StrUtil.isEmpty(url)) return false;
        try {
            URL netUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection();
            connection.setConnectTimeout(3000); //连接主机超时时间ms
            connection.setReadTimeout(3000); //从主机读取数据超时时间ms
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                System.out.println("网络联通!");
                return true;
            }
        } catch (IOException e) {
            log.error("连接不通", e.getMessage());
            return false;
        }
        return false;
    }

补充:下面看下url.openconnection() 设置超时时间

System.setProperty("sun.net.client.defaultConnectTimeout", "30000");  

System.setProperty("sun.net.client.defaultReadTimeout", "30000");  

其中: sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒)  

sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒)  

JDK 1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法:  

setConnectTimeout:设置连接主机超时(单位:毫秒)  

setReadTimeout:设置从主机读取数据超时(单位:毫秒)  

例如:  

HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();  

urlCon.setConnectTimeout(30000);  

urlCon.setReadTimeout(30000);  
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。