我已经浏览了各种Asynctask教程和示例,但我仍然有点困惑。如果我想发出3个web请求并返回它们的响应如:
//例子String[] response = new String[3];
response[0] = webrequest("http://www.google.com"); //simple HTTP GET request
response[1] = webrequest("http://www.bing.com"); //simple HTTP GET request
response[2] = webrequest("http://www.aj.com"); //simple HTTP GET request
//sample results from request
response[0] = "blah";
response[1] = "arg";
response[2] = "meh";
要用AsyncTask做到这一点,我需要实现3个不同的at吗?我应该用别的东西吗?
String[] response = new String[3];
webCreate sample = new webCreate();
try{
response[0] = sample.execute("http://www.google.com").get().toString();
response[1] = sample.execute("http://www.google.com").get().toString();
response[2] = sample.execute("http://www.google.com").get().toString();
}
catch (Exception sampleMsg)
{}
public class webCreate extends AsyncTask<String, String, String> {
}
protected String doInBackground(String... params) {
// String url=params[0];
String webRequestResponse = null; //the
// web request
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
return reponse;
}
我知道我可以通过使用。get()访问响应数据,但随后我的"Async"将变成"sync"lol。我觉得我应该使用AsyncTask以外的东西,但我不知道那是什么。请帮助。
你的方法是好的,从你的AsyncTask的doInBackground
调用一个函数,启动webrequests并等待. get()
的结果。由于请求没有在mainUi上运行并阻塞它,我认为这样做没有问题。