1

我正在尝试阅读 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) 
{
//
}

这是我得到的(一些)日志:

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. ... 

提前致谢。

4

2 回答 2

5

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

于 2012-07-24T18:12:34.957 回答
0

1.始终建议让UI 工作在 UI 线程上,而 Non-UI 工作在 Non-UI 线程上,这从 HoneyComb 版本的 Android开始成为一个规律。

此外尝试下面的代码....

public final String sUrl = "http://www.google.com";

new Thread(new Runnable(){

public void run(){

URL url = new URL(sUrl);

InputStream i = url.openStream();

InputStreamReader isr = new InputStreamReader(i);

BufferedReader br = new BufferedReader(isr);

StringBuilder sb = new StringBuilder();

String s = null;

while ((br.readLine())!=null){

  sb.append(br.readLine());

  }

  s = sb.toString();

 System.out.println(s);

     }
   }).start();

2.这个代码本来可以更小InputStream and Scanner但正如你所提到 BufferedReader的,我用它......

3.也可以使用AsyncTask专为android设计的无痛线程,轻松同步UI和Non-UI线程。

于 2012-07-24T18:19:09.670 回答