2012-01-12 81 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();