Android HTTP请求异步任务

Android HTTP请求异步任务,android,http-request,Android,Http Request,我想实现一个类,它将处理我的应用程序的所有HTTP请求,基本上是: 获取业务列表(Get) 执行登录(POST) 更新位置(POST) 因此,我必须从服务器(JSON)获取结果字符串,并将其传递给另一个方法来处理响应 我目前有以下几种方法: public class Get extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... arg) {

我想实现一个类,它将处理我的应用程序的所有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());
    }
公共类获取扩展异步任务{
@凌驾
受保护的字符串doInBackground(Void…arg){
字符串linha=“”;
字符串号=”;
mDialog=ProgressDialog.show(mContext,“Aguarde”,“Carregando…”,true);
//Cria o conexão客户
HttpClient=new DefaultHttpClient();
HttpGet=newhttpget(mUrl);
试一试{
//Faz a Clarcação HTTP
HttpResponse response=client.execute(get);
//请求的地位
StatusLine StatusLine=response.getStatusLine();
int statusCode=statusLine.getStatusCode();
如果(状态代码==200){//Ok
//佩加奥特雷诺
BufferedReader rd=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
//科洛卡·纳瓦里维尔酒店
而((linha=rd.readLine())!=null){
returno+=linha;
}
}
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回号;
}
@凌驾
受保护的void onPostExecute(字符串结果){
mDialog.discouse();
}
}
公共JSONObject getJSON(字符串url)抛出InterruptedException、ExecutionException{
//确定一个URL
setUrl(url);
//执行
Get g=新Get();
//雷托纳o jSON
返回createJSONObj(g.get());
}

但是
g.get()
返回一个空响应。我如何解决这个问题?

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

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

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

通过调用Get对象上的execute()函数,您似乎永远不会真正启动AsyncTask

请尝试以下代码:

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

我想你没有完全理解异步任务的工作方式。但我相信您希望为不同的任务重用代码;如果是这样,您可以创建一个抽象类,然后通过实现您创建的抽象方法对其进行扩展。应该这样做:

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

在doInBackground中添加一条log语句,该语句在get完成后记录字符串returno,以确保返回消息。我认为get()方法调用execute(),因为文档中说它等待计算完成。。。好的,我会尝试在之前调用它。那么,我如何处理对话框,使其在执行请求时显示,并在完成请求时关闭?这可能是正确的,但返回值不是来自.get方法,它会转到OnPostExecute。查看进入方法的字符串。这是您从HTTPConnection得到的响应。您可以很好地处理该对话框。问题是您想要的字符串是:protectedvoidonpostExecute(字符串结果)。这就是doInBackground返回的地方。而
.get()
在主线程上运行,有效地呈现了
异步任务的使用情况,这就是我要寻找的!谢谢