通过HttpURLConnection函数连接到互联网时,Android应用出现错误

时间:2018-09-08 03:11:47

标签: android httpurlconnection

我的功能是检测手机的互联网连接是否可用以及是否可以实际连接到互联网。

代码的第一部分运行良好,即检测手机的移动数据或wi-fi是否已打开。如果互联网已打开,则该函数尝试使用HttpURLConnection连接到网页,以检测互联网连接是否可以实际访问互联网。

不幸的是,该应用程序不断崩溃,并且根据logcat的错误,错误位于此代码urlc.connect()的行。

按照日志记录,MainActivity.java的第21行包含以下代码段:utils.network()。 Utils.java的第93行包含以下代码:urlc.connect()

public void network() {
    ConnectivityManager cm = (ConnectivityManager)_con.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    if (isConnected) {
        msg = "Internet Available";
        try {
            HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                msg += " and is connecting.";
            } else {
                msg += " but not connecting";
            }
            Log.e(TAG, "NO Error checking internet connection");
        } catch (IOException e) {
            Log.e(TAG, "Error checking internet connection", e);
        }
    } else {
        msg = "Internet Unavailable";
    }
    Toast toast = Toast.makeText(_con, msg, Toast.LENGTH_LONG);
    toast.show();
}

LOGCAT

09-08 06:02:00.534 4476-4476/com.appsite.appname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appsite.appname, PID: 4476
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appsite.appname/com.appsite.appname.MainActivity}: android.os.NetworkOnMainThreadException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5728)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
 Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1288)
    at java.net.InetAddress.lookupHostByName(InetAddress.java:432)
    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:253)
    at java.net.InetAddress.getAllByName(InetAddress.java:215)
    at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
    at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
    at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:368)
    at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:351)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:341)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:259)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:454)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
    at com.appsite.appname.utils.Utils.network(Utils.java:93)
    at com.appsite.appname.MainActivity.onCreate(MainActivity.java:21)
    at android.app.Activity.performCreate(Activity.java:6301)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2519)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488) 
    at android.os.Handler.dispatchMessage(Handler.java:111) 
    at android.os.Looper.loop(Looper.java:207) 
    at android.app.ActivityThread.main(ActivityThread.java:5728) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 

2 个答案:

答案 0 :(得分:1)

您正在主线程上发出网络请求。使用后台线程发出网络请求。这是问题的根源。

Caused by: android.os.NetworkOnMainThreadException

答案 1 :(得分:1)

在创建时尝试以下行

StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);