Android的HTTP请求的AsyncTaskAndroid、HTTP、AsyncTask

2023-09-12 03:36:44 作者:怂比°

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

I want to implement a class which will handle all HTTP Requests of my application, which will be basically:

在获取企业名单(GET); 执行登录(POST); 更新位置(POST)。

所以,我必须从服务器(JSON)得到的结果字符串,并将其传递给另一个方法来处理响应。

So, I will have to get the result string from the server (JSON) and pass it to another methods to handle the responses.

目前,我有这样的方法:

I currently have this methods:

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()返回一个空的响应。我该如何解决呢?

But the g.get() returns a empty response. How can I fix that?

推荐答案

我觉得你并没有完全理解的AsyncTask的工作方式。不过,我相信你想重新使用code不同的任务;如果是这样,你可以创建一个抽象类,然后扩展它实现你创建了一个抽象方法。它应该这样做:

I think you didn't understand exactly the way AsyncTask works. But I believe you wish to reuse the code for different tasks; if so, you can create an abstract class and then extend it implementing an abstract method you created. It should be done like this:

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);
}

然后再根据您的活动在code应该是这样的:

And then the code on your activity should be something like this:

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