【问题标题】:Android HTTP Request AsyncTaskAndroid HTTP 请求 AsyncTask
【发布时间】:2012-01-12 01:46:42
【问题描述】:

我想实现一个类来处理我的应用程序的所有 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 完成后记录 String returno 以确保返回消息。

标签: android http-request


【解决方案1】:

我认为您并不完全了解 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);

【讨论】:

  • 这就是我想要的!谢谢!
【解决方案2】:

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

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

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

【讨论】:

  • 我以为get()方法调用execute(),因为文档说它等待计算完成...好吧,我会尝试调用它之前。
  • 那么如何处理在请求执行时出现的对话框并在完成时关闭?
  • 这可能是对的,但返回值不是来自 .get 方法,它会转到您的 OnPostExecute。查看方法中的字符串。那是你从 HTTPConnection 的回应。
  • 你处理对话框就好了。问题是你想要的字符串是这个:protected void onPostExecute(String result)。这就是 doInBackground 的返回值。
  • .get()在主线程上运行,有效地呈现AsyncTask void的用法
【解决方案3】:

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

试试这个代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多