通过异步任务逐个下载网站内容

时间:2016-07-22 11:11:39

标签: java android android-studio android-asynctask

我有一个应用程序,我尝试使用Async任务管理器下载 url ArrayList ,然后逐个显示每个网站的内容。我很困惑请帮助我。我也尝试在执行方法上使用 for 循环,但它给我一个错误。

请让我知道我必须使用所需的代码。

感谢。

异步任务

public class DownloadWeb extends AsyncTask<String,Void,String>{
    @Override
    protected String doInBackground(String... urls) {
        String result = "";
        HttpURLConnection connection;

        URL myUrl;

        try{

            myUrl = new URL(urls[0]);
            connection = (HttpURLConnection) myUrl.openConnection();

            //!!!!!!!!! The page will not re direct!!!!!!!!!!!!!!!!//


            String redirect = connection.getHeaderField("Location");

            if(redirect != null){

                connection = (HttpURLConnection) new URL(redirect).openConnection();

            }


            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            String line = "";
            StringBuilder stringBuilder = new StringBuilder();

            while((line=reader.readLine()) != null){

                stringBuilder.append(line);
                result = stringBuilder.toString();

            }

            return result;




        }

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

        }




        return null;
    }
}

onCreate方法

DownloadWeb task = new DownloadWeb();
    try {
        String res = task.execute(arr.get(0)).get();




    }

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

1 个答案:

答案 0 :(得分:0)

尝试在Executor上执行异步任务

asyncTask1.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
// asyncTask2 will only be done AFTER asyncTask1 is done
asyncTask2.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);

或者您可以创建自定义队列并执行在那里添加asyncTask

参考https://developer.android.com/reference/android/os/AsyncTask.html#SERIAL_EXECUTOR