Android从网上阅读内容

时间:2016-08-15 06:36:15

标签: android multithreading

版本1

@Override
protected String doInBackground(String... urls) {
    String result = "";
    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(urls[0]);
        urlConnection = (HttpURLConnection)url.openConnection();
        InputStream in = urlConnection.getInputStream();
        InputStreamReader reader = new InputStreamReader(in);

        BufferedReader r = new BufferedReader(reader);
        StringBuilder total = new StringBuilder();
        String line = "";
        while ((line = r.readLine()) != null) {
            total.append(line).append('\n');
        }
        result = total.toString();
        return result;

    }
    catch(Exception e) {
        e.printStackTrace();
        return "Failed";
    }
  }
}

第2版

@Override
protected String doInBackground(String... urls) {
    String result = "";
    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(urls[0]);
        urlConnection = (HttpURLConnection)url.openConnection();
        InputStream in = urlConnection.getInputStream();
        InputStreamReader reader = new InputStreamReader(in);

        int data = reader.read();
        while (data != -1) {
            char current = (char) data;
            result += current;
        data = reader.read();
        }
        result = total.toString();
        return result;

    }
    catch(Exception e) {
        e.printStackTrace();
        return "Failed";
    }
  }

}

基本上,我试图通过扩展AsynTask来阅读网站的HTML内容。两个代码之间的唯一区别是我正在阅读的方式并将内容作为字符串返回。版本1 工作,但版本2工作。我的问题是为什么版本1不起作用?我将内容存储在缓冲区读取器中并将其放入StringBuilder并将其显示为字符串,如图所示。

0 个答案:

没有答案