2015-06-02 77 views
0

我一直在討論各種Asynctask教程和示例,但我仍然有點困惑。如果我要發出3個Web請求並返回其響應 ,如:AsyncTask完整性檢查

//例如

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; 
    } 

我知道我可以通過獲得()訪問響應數據,但後來我的「異步」將成爲「同步」笑。我覺得我應該使用AsyncTask以外的東西,但我不知道那是什麼。請幫忙。

+0

請勿使用AsyncTasks。改爲考慮Volley/Retrofit/Loaders/RxJava。 –

+0

AsyncTasks是在啓動API中嘗試簡化線程使用的失敗嘗試。隨着時間的推移,人們發現它們並不完美,它們是回調地獄,也是泄漏的背景。儘可能避免。 –

回答

0

您的方法沒問題,從您的AsyncTask的doInBackground調用一個函數啓動webrequests並等待. get()的結果。由於這個事實,這個請求並沒有在mainUi上運行並且被阻塞,我看到這樣做沒有問題。