How to quickly check if URL server is available

后端 未结 8 2030
执念已碎
执念已碎 2020-12-09 16:30

I have a URL in the form

http://www.mywebsite.com/util/conv?a=1&from=%s&to=%s

And want to check if it is available.

The lin

相关标签:
8条回答
  • 2020-12-09 16:41
    if (android.os.Build.VERSION.SDK_INT > 9) {
                                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                                        .permitAll().build();
    
                                StrictMode.setThreadPolicy(policy);
                            }
                            try {
                                URL diachi = new URL("http://example.com");
                                HttpURLConnection huc = (HttpURLConnection) diachi.openConnection();
                                huc.setRequestMethod("HEAD");
                                int responseCode = huc.getResponseCode();
    
                                if (responseCode != 404) {
                                    //URL Exist
    
                                } else {
                                    //URL not Exist
                                }
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
    
    0 讨论(0)
  • 2020-12-09 16:42

    I had similar problem last month and someone helped me out with an optional example. I'd like to suggest you the same

    public boolean isServerReachable()
        // To check if server is reachable
        {
            try {
                InetAddress.getByName("google.com").isReachable(3000); //Replace with your name
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    

    if return true than your url server is available else is not available currently.

    0 讨论(0)
  • 2020-12-09 16:47
    public static boolean exists(String URLName) {
    
            try {
                HttpURLConnection.setFollowRedirects(false);
                // note : you may also need
                // HttpURLConnection.setInstanceFollowRedirects(false)
                HttpURLConnection con = (HttpURLConnection) new URL(URLName)
                .openConnection();
                con.setRequestMethod("HEAD");
                return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    0 讨论(0)
  • 2020-12-09 16:49
    static public boolean isServerReachable(Context context) {
        ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connMan.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL urlServer = new URL("your server url");
                HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
                urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout 
                urlConn.connect();
                if (urlConn.getResponseCode() == 200) {
                    return true;
                } else {
                    return false;
                }
            } catch (MalformedURLException e1) {
                return false;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }
    

    or by using runtime:

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("ping www.serverURL.com"); //<- Try ping -c 1 www.serverURL.com
    int mPingResult = proc .waitFor();
    if(mPingResult == 0){
        return true;
    }else{
        return false;
    }
    

    You can try isReachable() but there is a bug filed for it and this comment says that isReachable() requires root permission:

    try {
        InetAddress.getByName("your server url").isReachable(2000); //Replace with your name
        return true;
    } catch (Exception e)
    {
        return false;
    }
    
    0 讨论(0)
  • 2020-12-09 16:50

    here the writer suggests this:

    public boolean isOnline() {
        Runtime runtime = Runtime.getRuntime();
        try {
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException | InterruptedException e) { e.printStackTrace(); }
        return false;
    }
    

    Couldn’t I just ping my own page, which I want to request anyways?Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable

    read the link. its seems very good

    EDIT: in my exp of using it, it's not as fast as this method:

    public boolean isOnline() {
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }
    

    they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.

    0 讨论(0)
  • 2020-12-09 16:52

    have you tried using raw sockets?

    It should run faster as it's on a lower layer

    static boolean exists(String serverUrl)  {
    
        final Socket socket;
    
        try {
            URL url = new URL(serverUrl);
            socket = new Socket(url.getHost(), url.getPort());
        } catch (IOException e) {
            return false;
        }
    
        try {
            socket.close();
        } catch (IOException e) {
            // will never happen, it's thread-safe
        }
    
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题