Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: AsyncTask to make an HTTP GET Request?

I'm new to Android development. My question is, do I use AsyncTask in order to make an HTTP GET request (JSON response)? Is this correct? Does anyone know where I can see an example of this if this is indeed true? If not, could you correct me? Thanks!

like image 547
Mario A Guzman Avatar asked Jun 25 '14 02:06

Mario A Guzman


People also ask

Is AsyncTask deprecated in Android?

This class was deprecated in API level 30.

How do I use AsyncTask?

Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.

What is AsyncTask?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

How many methods are there for AsyncTask class?

An AsyncTask is an abstract Java class that moves intensive processing onto a separate thread. AsyncTask must be subclassed to be used. AsyncTask has 4 useful methods: onPreExecute() , doInBackground() , onPostExecute() and onProgressUpdate() .


2 Answers

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

}
like image 129
Rod_Algonquin Avatar answered Sep 20 '22 06:09

Rod_Algonquin


protected String doInBackground(String... strings) {

    String response = "";

    response = ServiceHandler.findJSONFromUrl("url");
    data = response;
    return response;
}

public class ServiceHandler {

    // Create Http connection And find Json

    public static String findJSONFromUrl(String url) {
        String result = "";
        try {
            URL urls = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
            conn.setReadTimeout(150000); //milliseconds
            conn.setConnectTimeout(15000); // milliseconds
            conn.setRequestMethod("GET");

            conn.connect();

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");

                }
                result = sb.toString();
            } else {

                return "error";
            }


        } catch (Exception e) {
            // System.out.println("exception in jsonparser class ........");
            e.printStackTrace();
            return "error";
        }

        return result;
    } // method ends
}
like image 35
Rishabh Dixit Avatar answered Sep 18 '22 06:09

Rishabh Dixit