Android: AsyncTask to make an HTTP GET Request?

前端 未结 7 761
失恋的感觉
失恋的感觉 2020-11-27 19:46

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 a

7条回答
  •  误落风尘
    2020-11-27 20:10

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

提交回复
热议问题