2012-01-12 85 views
4

我想實現一個類,它將處理我的申請,所有的HTTP請求,這將是基本上是:Android的HTTP請求的AsyncTask

  • 獲取業務(GET)的列表;
  • 執行登錄(POST);
  • 更新位置(POST)。

所以,我將不得不從服務器(JSON)得到結果字符串,並將其傳遞給另一個方法來處理響應。

我現在有這樣的方法:

public class Get extends AsyncTask<Void, Void, String> { 
    @Override 
    protected String doInBackground(Void... arg) { 
     String linha = ""; 
     String retorno = ""; 

     mDialog = ProgressDialog.show(mContext, "Aguarde", "Carregando...", true); 

     // Cria o cliente de conexão 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet get = new HttpGet(mUrl); 

     try { 
      // Faz a solicitação HTTP 
      HttpResponse response = client.execute(get); 

      // Pega o status da solicitação 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 

      if (statusCode == 200) { // Ok 
       // Pega o retorno 
       BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

       // Lê o buffer e coloca na variável 
       while ((linha = rd.readLine()) != null) { 
        retorno += linha; 
       } 
      } 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return retorno; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     mDialog.dismiss(); 
    } 
} 

    public JSONObject getJSON(String url) throws InterruptedException, ExecutionException { 
     // Determina a URL 
     setUrl(url); 

     // Executa o GET 
     Get g = new Get(); 

     // Retorna o jSON 
     return createJSONObj(g.get()); 
    } 

g.get()返回一個空的響應。我該如何解決這個問題?

+0

添加日誌語句將doInBackground用來記錄字符串returno的get後就一直完成以確保消息正在返回。 – 2012-01-12 01:57:04

回答

12

我想你沒有完全理解的AsyncTask的工作方式。但我相信你希望重用代碼來完成不同的任務;如果是這樣,你可以創建一個抽象類,然後擴展它實現你創建的抽象方法。它應該做的事是這樣的:

public abstract class JSONTask extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... arg) { 
     String linha = ""; 
     String retorno = ""; 
     String url = arg[0]; // Added this line 

     mDialog = ProgressDialog.show(mContext, "Aguarde", "Carregando...", true); 

     // Cria o cliente de conexão 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet get = new HttpGet(mUrl); 

     try { 
      // Faz a solicitação HTTP 
      HttpResponse response = client.execute(get); 

      // Pega o status da solicitação 
      StatusLine statusLine = response.getStatusLine(); 
      int statusCode = statusLine.getStatusCode(); 

      if (statusCode == 200) { // Ok 
       // Pega o retorno 
       BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

       // Lê o buffer e coloca na variável 
       while ((linha = rd.readLine()) != null) { 
        retorno += linha; 
       } 
      } 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return retorno; // This value will be returned to your onPostExecute(result) method 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // Create here your JSONObject... 
     JSONObject json = createJSONObj(result); 
     customMethod(json); // And then use the json object inside this method 
     mDialog.dismiss(); 
    } 

    // You'll have to override this method on your other tasks that extend from this one and use your JSONObject as needed 
    public abstract customMethod(JSONObject json); 
} 

,然後在你的活動代碼應該是這樣的:

YourClassExtendingJSONTask task = new YourClassExtendingJSONTask(); 
task.execute(url); 
+0

+1謝謝,您的回答可以幫助我! – sfratini 2012-01-12 02:24:19

+0

,因此可以有效地呈現「AsyncTask」的使用效果void – 2012-01-12 17:23:49

+0

這就是我正在尋找的!謝謝 ! – Matthias 2014-06-24 14:57:17

1

您沒有執行任務。你只是在創造它。我認爲你需要:

Get g = new Get(); 
g.execute(); 

但是你正在以錯誤的方式使用任務的生命週期。 OnPostExecute在主線程上運行,您應該根據需要執行所有更新。例如,您可以將任務傳遞給View。

+0

我以爲get()方法調用execute(),因爲文檔說它等待計算完成......好吧,我會嘗試在之前調用它。 – 2012-01-12 02:25:43

+0

那麼如何處理在執行請求時出現的對話框,並在完成時解除對話框? – 2012-01-12 02:27:13

+1

這可能是正確的,但返回值不是來自.get方法,而是返回到OnPostExecute。查看進入該方法的字符串。這就是你從HTTPConnection的迴應。 – sfratini 2012-01-12 02:33:03

1

看起來您從來沒有真正通過調用Get對象的execute()函數來啓動AsyncTask。

試試這個代碼:

Get g = new Get(); 
g.execute();