5

我想实现一个类来处理我的应用程序的所有 HTTP 请求,基本上是:

  • 获取业务列表(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()返回一个空响应。我该如何解决?

4

3 回答 3

14

我认为您并不完全了解 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);
于 2012-01-12T02:15:01.293 回答
1

您没有执行任务。你只是在创造它。我认为你需要做:

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

但是您以错误的方式使用任务的生命周期。OnPostExecute 在主线程上运行,您应该根据需要在其中进行所有更新。例如,您可以将任务传递给视图。

于 2012-01-12T02:05:32.397 回答
1

您似乎从未真正通过调用 Get 对象上的 execute() 函数来启动 AsyncTask。

试试这个代码:

Get g = new Get();
g.execute();
于 2012-01-12T02:08:47.240 回答