Android: Asynctask to Make an Http Get Request

Android: AsyncTask to make an HTTP GET Request?

Yes you are right, Asynctask is used for short running task such as connection to the network. Also it is used for background task so that you wont block you UI thread or getting exception because you cant do network connection in your UI/Main thread.

example:

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected Boolean doInBackground(String... urls) {
try {

//------------------>>
HttpGet httppost = new HttpGet("YOU URLS TO JSON");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);

// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();

if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);

JSONObject jsono = new JSONObject(data);

return true;
}

} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {

e.printStackTrace();
}
return false;
}

protected void onPostExecute(Boolean result) {

}

Android HTTP: Make more than 1 asynctask request

Pass one more argument to the AsyncTask. Make some constants corresponding to your tasks.

new DownloadTask().execute("http://www.google.com/", DownloadTask.ID_ASYNC1);
new DownloadTask().execute("http://www.facebook.com/", DownloadTask.ID_ASYNC2);
new DownloadTask().execute("http://www.twitter.com/", DownloadTask.ID_ASYNC3);

Inside AsyncTask, use this id to identify which is the request being called.

private class DownloadTask extends AsyncTask<String, Void, String> {
//Variable for storing the req id
private int id;

//Constants corresponding to your tasks
public static int ID_ASYNC1 = 0;
static static int ID_ASYNC1 = 0;
static static int ID_ASYNC1 = 0;

@Override
protected String doInBackground(String... params) {
id = params[1]);
//your code
}

@Override
protected void onPostExecute(String result) {
if(id == ID_ASYNC1){
//Do your task #1
} else if(id == ID_ASYNC2){
//Do your task #2
}
}
}

Android HTTP Request AsyncTask

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

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

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

How to make Apache HTTP request from AsyncTask

I guess your problem is with parameters.

Try sth like this:

 HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("your url");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

nameValuePair.add(new BasicNameValuePair("username", "username"));
nameValuePair.add(new BasicNameValuePair("lang", "en"));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePair);
HttpResponse response = httpClient.execute(httpPost);

Hope it will help.

EDIT
And I just found another possible solution for your problem:
Here

android execute HTTP request without AsyncTask?

I suggest taking a look at the Android Asynchronous Http Client (Loopj) library. Here's an example of a "typical" http request.

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});


Related Topics



Leave a reply



Submit