Android HTTP 请求 AsyncTask

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()返回了一个空响应,我该怎么解决呢?

在你的doInBackground中添加一个日志语句,记录get完成后返回的字符串returno,以确保消息被返回。 - coder_For_Life22
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);
}

然后,你的Activity上的代码应该类似于这样:

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

这正是我在寻找的!谢谢! - Matthias

1

你并没有执行任务,只是创建了它。我认为你需要做的是:

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

但是你正在错误地使用任务的生命周期。OnPostExecute在主线程上运行,您应该根据需要进行所有更新。例如,您可以向任务传递一个View。


我以为get()方法会调用execute(),因为文档说它会等待计算完成...好的,我会在之前尝试调用它。 - Danniel Magno
那么我该如何处理对话框,使其在请求执行时出现,并在完成后关闭? - Danniel Magno
1
可能是对的,但返回值不是来自.get方法,而是传递给你的OnPostExecute。查看传入方法的字符串,那就是你的HTTPConnection响应。 - sebastianf182
你已经很好地处理了对话框。问题在于你想要的字符串是这个:protected void onPostExecute(String result)。这就是doInBackground返回的地方。 - sebastianf182
“.get()” 运行在主线程上,这有效地使得使用“AsyncTask”无效。 - slinden77

1

看起来您从未通过在Get对象上调用execute()函数来启动AsyncTask。

尝试使用以下代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接