如何知道android中可访问的服务器?

时间:2015-06-25 10:20:05

标签: android server wifi

嗨,我想知道我的网站是否可访问或可用?

使用此方法我知道我的设备是否在线:

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

使用此方法我想知道URL是否可用:

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

然后我创建了一个Button,当点击这两个方法时会调用,如下所示:

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

单击按钮,如果WiFi关闭,此消息将显示:

  

您没有连接到互联网!

当WiFi开启时,此错误将显示:

> 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

如何确定服务器是否可用?

谢谢你。

2 个答案:

答案 0 :(得分:1)

Asynctask调用您的方法isServerReachable()

由于您在应用程序的主线程上进行网络调用,因此崩溃。

答案 1 :(得分:1)

该错误是由isServerReachable()方法引起的,因为您正在UI线程中执行网络操作,这将导致NetworkOnMainThreadException。而是直接运行它们来执行AsyncTask或其他工作人员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.
        }
    }