I want to implement a class which will handle all HTTP Requests of my application, which will be basically:
- Get a list of business (GET);
- Execute a login (POST);
- Update the location (POST).
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());
}
But the g.get()
returns a empty response. How can I fix that?
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:
And then the code on your activity should be something like this: