AsyncTask de solicitud HTTP de Android
-
27-10-2019 - |
Pregunta
Quiero implementar una clase que maneje todas las solicitudes HTTP de mi aplicación, que serán básicamente:
- Obtener una lista de empresas (GET);
- Ejecute un inicio de sesión (POST);
- Actualice la ubicación (POST).
Entonces, tendré que obtener la cadena de resultado del servidor (JSON) y pasarla a otros métodos para manejar las respuestas.
Actualmente tengo estos métodos:
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());
}
Pero g.get()
devuelve una respuesta vacía.¿Cómo puedo solucionarlo?
Solución
Creo que no entendiste exactamente cómo funciona AsyncTask.Pero creo que desea reutilizar el código para diferentes tareas;si es así, puede crear una clase abstracta y luego extenderla implementando un método abstracto que creó.Debería hacerse así:
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);
}
Y luego el código de tu actividad debería ser algo como esto:
YourClassExtendingJSONTask task = new YourClassExtendingJSONTask();
task.execute(url);
Otros consejos
No está ejecutando la tarea.Solo lo estás creando.Creo que necesitas hacer:
Get g = new Get();
g.execute();
Pero está utilizando el ciclo de vida de la tarea de forma incorrecta.OnPostExecute se ejecuta en el hilo principal, donde debe hacer todas las actualizaciones según sea necesario.Puede pasar la tarea a una Vista, por ejemplo.
Parece que nunca está iniciando AsyncTask llamando a la función execute () en el objeto Get.
prueba este código:
Get g = new Get();
g.execute();