• URLAvailability


    import org.springframework.stereotype.Component;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    @Component
    public class URLAvailability {
        private static URL url;
        private static HttpURLConnection con;
        private static int state = -1;
    
        /**
         * 功能:检测当前URL是否可连接或是否有效,
         * 描述:最多连接网络 5 次, 如果 5 次都不成功,视为该地址不可用
         *
         * @param urlStr 指定URL网络地址
         * @return URL
         */
        public synchronized String  isConnect(String urlStr) {
            int counts = 0;
            if (urlStr == null || urlStr.length() <= 0) {
                return null;
            }
            while (counts < 5) {
                try {
                    url = new URL(urlStr);
                    con = (HttpURLConnection) url.openConnection();
                    state = con.getResponseCode();
                    System.out.println(counts + "= " + state);
                    if (state == 200) {
                        System.out.println("URL可用!");
                    }
                    break;
                } catch (Exception ex) {
                    counts++;
                    System.out.println("URL不可用,连接第 " + counts + " 次");
                    urlStr = null;
                    continue;
                }
            }
           return  urlStr;
        }
    
    
    
        public static void main(String[] args) {
            URLAvailability u = new URLAvailability();
    //        http://localhost:18082/api/get/1
            String url = u.isConnect("http://127.0.0.1:18082/api/");
            System.out.println(url+"addScreen/");
           String posturl1="http://127.0.0.1:18089/api/";
           String posturl2="http://127.0.0.1:18082/api/";
           String posturl3="http://127.0.0.1:18084/api/";
    
                String posturl = null;
                if (null == u.isConnect(posturl1)) {
                    if (null == u.isConnect(posturl2)) {
                        if (null == u.isConnect(posturl3)) {
                            posturl = null;
                        } else {
                            posturl = posturl3;
                        }
                    } else {
                        posturl = posturl2;
                    }
                } else {
                    posturl = posturl1;
                }
            System.out.println(posturl);
    
    
    
        }
    }
  • 相关阅读:
    IIS7开启目录浏览功能
    IIS7文件无法下载问题处理
    Dubbo端口占用错误信息
    PlSqlDev中执行INSERT SQL语句包含&符号导致数据异常
    VMWare版本兼容问题处理
    手动释放Linux内存
    ORA-00972_标识符过长
    通过API获取统计信息时报Access denied错误处理记录
    微信小程序中跳转另一个小程序
    css怎样去掉多个Img标签之间的间隙
  • 原文地址:https://www.cnblogs.com/tonggc1668/p/15231981.html
Copyright © 2020-2023  润新知