简体   繁体   中英

How to know the server in reachable or not in android?

Hi, I want to know is my website in reachable or available?

whit this method I know my device is online or not:

protected boolean isOnline() {

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            Toast.makeText(this, "You are connecting to Internet!", Toast.LENGTH_LONG).show();
            return true;
        } else {
            Toast.makeText(this, "You are not connecting to Internet!", Toast.LENGTH_LONG).show();
            return false;
        }
    }

and with this method I want to know is URL available or not:

public boolean isServerReachable(String serverURL) {

        ConnectivityManager connMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connMan.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL urlServer = new URL(serverURL);
                HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
                urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout
                urlConn.connect();
                if (urlConn.getResponseCode() == 200) {
                    Toast.makeText(this, "Server is Available", Toast.LENGTH_LONG).show();
                    return true;
                } else {
                    Toast.makeText(this, "Server is not Available", Toast.LENGTH_LONG).show();
                    return false;
                }
            } catch (MalformedURLException e1) {
                return false;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }

then I create a Button, when clicked this two method will call, like this:

if (isOnline()) {
    isServerReachable("https://www.google.com/");
 }

when I click the Button if WiFi is Off this Message will show:

You are not connecting to Internet!

and when WiFi is On this error will show:

> Process: com.rastari.salar.salytest, PID: 3864
>     android.os.NetworkOnMainThreadException
>             at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
>             at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
>             at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
>             at java.net.InetAddress.getAllByName(InetAddress.java:215)
>             at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
>             at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
>             at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
>             at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
>             at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
>             at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
>             at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
>             at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
>             at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
>             at com.rastari.salar.salytest.MainActivity.isServerReachable(MainActivity.java:78)
>             at com.rastari.salar.salytest.MainActivity$1.onClick(MainActivity.java:37)
>             at android.view.View.performClick(View.java:4780)
>             at android.view.View$PerformClick.run(View.java:19866)
>             at android.os.Handler.handleCallback(Handler.java:739)
>             at android.os.Handler.dispatchMessage(Handler.java:95)
>             at android.os.Looper.loop(Looper.java:135)
>             at android.app.ActivityThread.main(ActivityThread.java:5254)
>             at java.lang.reflect.Method.invoke(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:372)
>             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
>             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 06-25
> 06:14:16.845    1557-1557/? E/EGL_emulation﹕ tid 1557:
> eglCreateSyncKHR(1207): error 0x3004 (EGL_BAD_ATTRIBUTE) 06-25
> 06:14:17.614    1708-1891/? E/WifiStateMachine﹕ CMD_START_SCAN :
> connected mode and no configuration

How can I determine that the server is available or not?

Thank u.

Call your method isServerReachable() from an Asynctask .

Since your doing a network call on main thread of your application, it crashes.

The error is due to isServerReachable() method because you are doing the networking operations in the UI thread, which will result NetworkOnMainThreadException . Instead to running them directly execute the method in a AsyncTask or another worker Thread .

 public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            return isServerReachable(URl);
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            //Perform operations.
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM