首页 > 代码库 > android网络访问异常:android.os.NetworkOnMainThreadException

android网络访问异常:android.os.NetworkOnMainThreadException

 Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:388)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)
            at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
            at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
            at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
            at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
            at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
            at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
            at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
            at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
            at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)

            at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)

在2.3的手机上运行是没有问题的,在2.3后的手机上运行就会出现此异常。

在2.3之后的android不允许在主线程中访问网络,因为访问网络是耗时操作,如果在主线程中访问网络,在网络访问慢时,用户界面会假死,造成Android not Response,为了避免这个问题,2.3之后做了限制,必须将耗时操作放在子线程中完成!!!

android网络访问异常:android.os.NetworkOnMainThreadException