Android Studio - HttpUrlConnection& BufferedReader没有读取所有内容?

时间:2017-05-21 01:30:09

标签: android inputstream httpurlconnection bufferedreader

因此,当在较小的页面上运行此代码时,它运行正常。但是当我在一个更大的页面上运行它时,例如Stackoverflow或其他任何东西,它都没有在String结果中获得完整的源代码。有什么我不考虑或做错的家伙吗?谢谢!

示例:对于StackOverflow,它在源代码的第35行停止只有几个字符,而不是3000多行代码。

日志的最后一行:

  

StackExchange.using(" GP

我的代码:

protected void runItNow(View v){
    Log.i("INSIDE: ", "runItNow");

    DownloadTask downloadTask = new DownloadTask();
    String result;
    try {
        result = downloadTask.execute("http://www.stackoverflow.com/").get();


    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }


}

private class DownloadTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {
        URL url;
        HttpURLConnection urlConnection;

        try{

            url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            urlConnection.setConnectTimeout(250000);

            int data;
            char[] buffer = new char[4096];
            StringBuilder builder = new StringBuilder();

            while ((data = reader.read(buffer)) != -1){
                builder.append(buffer, 0, data);
            }

            String results = builder.toString();
            Log.i("Results: ", results);


            in.close();
            reader.close();
            urlConnection.disconnect();
            return results;


        }catch(Exception e){
            e.printStackTrace();
        }

        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

您是否仅使用Log.i("Results: ", results);检查输出? Logcat可能正在削减其余的角色。尝试将其写入文件并检查其内容。