创建BufferedReader以读取导致错误的URL:无法启动活动

NS1*_*114 1 java android urlconnection bufferedreader

我正在尝试阅读URL的内容.BufferedReader的初始化会导致崩溃.

我试过查找人们的解决方案,但无论我做什么,我都会遇到这个错误.

这是我的代码:

 try {
        String sUrl = "http://www.google.com";
        System.out.println("About to create URL.");
        URL url = new URL(sUrl);
        System.out.println("Created URL");

        System.out.println("About to create URLConnection");
        URLConnection urlc = url.openConnection();
        System.out.println("Created URLConnection");

        System.out.println("About to create the BufferedReader");
        BufferedReader bR = new BufferedReader(new 
            InputStreamReader(urlc.getInputStream()));
        System.out.println("Created the BufferedReader");

        System.out.println("About to create a StringBuilder");
        StringBuilder sBuilder = new StringBuilder();
        System.out.println("Created StringBuilder");

        int byteRead;
        System.out.println("About to enter while loop and build string");
        while ((byteRead = bR.read()) != -1)
        {
            sBuilder.append((char) byteRead);
        }
        System.out.println("Built string");

        bR.close();
        System.out.println("Buffered reader is closed");
        String text = sBuilder.toString();
        System.out.println(text);
} 
catch (IOException e) 
{
//
}
Run Code Online (Sandbox Code Playgroud)

这里有(部分)我得到的日志:

07-24 13:56:17.546: I/System.out(1554): About to create URL.
07-24 13:56:17.557: I/System.out(1554): Created URL
07-24 13:56:17.557: I/System.out(1554): About to create URLConnection
07-24 13:56:17.557: I/System.out(1554): Created URLConnection
07-24 13:56:17.557: I/System.out(1554): About to create the BufferedReader
07-24 13:56:17.576: D/AndroidRuntime(1554): Shutting down VM
07-24 13:56:17.576: W/dalvikvm(1554): threadid=1: thread exiting with uncaught exception   
                                      (group=0x40a13300)
07-24 13:56:17.606: E/AndroidRuntime(1554): FATAL EXCEPTION: main
07-24 13:56:17.606: E/AndroidRuntime(1554): java.lang.RuntimeException: Unable to start 
                                     activity ComponentInfo{com. ... 
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Jox*_*aex 5

从Android 3.0开始,在主UI线程中打开URL连接是不合法的.你必须在AsyncTask/Background线程中执行此操作.