【发布时间】:2016-07-22 11:11:39
【问题描述】:
我有一个应用程序,我正在尝试使用异步任务管理器下载 urls 的 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();
}
【问题讨论】:
-
首先不要在 AsyncTask 上使用 .get()。非常糟糕的编程。
-
but it thorws me an error.。如果是这样,那么您当然应该说出错误并最好发布 LogCat。 -
show the content of per website one by one。一张一张地显示页面?什么时候应该更改这样的页面?谁会触发对新页面的更改以及何时触发?您的代码中没有任何内容显示您如何处理结果。
标签: java android android-studio android-asynctask