简体   繁体   中英

method getInputStream() in HttpURLConnection in Android always failed

HttpURLConnection urlConn = (HttpURLConnection) new URL(
                "http://www.google.com").openConnection();

        InputStream is = urlConn.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            result += inputLine;
        }

When it comes to urlConn.getInputStream(), it fails. But the same code works in normal java project instead of Android project.

And I find that in Android, when it runs the first statement, urlConn is:"libcore.net.http.HttpURLConnectionImpl:http://www.google.com"

But in normal java project, it is "sun.net.www.protocol.http.HttpURLConnection:http://www.google.com"

Thanks!!

Exception stack:

11-21 21:14:01.750: I/System.out(20784): debugger has settled (1392)
11-21 21:14:56.380: W/dalvikvm(20784): threadid=1: thread exiting with uncaught exception (group=0x410e49d8)
11-21 21:14:56.420: E/AndroidRuntime(20784): FATAL EXCEPTION: main
11-21 21:14:56.420: E/AndroidRuntime(20784): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.network/com.example.network.MainActivity}: android.os.NetworkOnMainThreadException
11-21 21:14:56.420: E/AndroidRuntime(20784):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1969)
11-21 21:14:56.420: E/AndroidRuntime(20784):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1994)
11-21 21:14:56.420: E/AndroidRuntime(20784):    at android.app.ActivityThread.access$600(ActivityThread.java:126)

I have added the INTERNET permission.

Ahh that famous android.os.NetworkOnMainThreadException :)

Starting from HoneyComb , network operations - by default - are not allowed to be executed over main (UI) thread. Therefore, use AsyncTask or Thread to perform this operation on a separate thread.

Do not do networking on UT thread (NetworkOnMainThreadException). Use AsyncTask to avoid this exception

See this article for more details: http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

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