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);



    }
}

 

posted @ 2021-09-06 00:05  tonggc1668  阅读(33)  评论(0编辑  收藏  举报