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

当涉及到 urlConn.getInputStream() 时,它失败了。但是相同的代码适用于普通的 java 项目而不是 Android 项目。

而且我发现在Android中,当它运行第一条语句时, urlConn 是:“libcore.net.http.HttpURLConnectionImpl:http://www.google.com”

但在普通的java项目中,它是“sun.net.www.protocol.http.HttpURLConnection:http://www.google.com”

谢谢!!

异常堆栈:

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)

我已经添加了 INTERNET 权限。

4

2 回答 2

3

啊那个有名的android.os.NetworkOnMainThreadException:)

HoneyComb开始,网络操作 - 默认情况下 - 不允许在主(UI)线程上执行。因此,使用AsyncTaskThread在单独的线程上执行此操作。

于 2012-11-21T13:51:34.447 回答
2

不要在 UT 线程上进行联网 (NetworkOnMainThreadException)。使用 AsyncTask 避免此异常

有关更多详细信息,请参阅本文:http ://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html

于 2012-11-21T13:52:43.590 回答