Android: AsyncTask to make an HTTP GET Request?

前端 未结 7 742
失恋的感觉
失恋的感觉 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:11

    Yes you have 3 choices

    1. Using AsyncTask
    2. You can use Handler
    3. or you can use a seperate Thread.

    Best choice is AsyncTask. You have to implement your network call in doInBackground method of AsyncTaskand in postExecute method update the UI or whatever you want to do with the result.

    you can follow follow this tutorial for your requirement

    code snippet

    @Override
        protected String doInBackground(String... urls) {
          String response = "";
          for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
              HttpResponse execute = client.execute(httpGet);
              InputStream content = execute.getEntity().getContent();
    
              BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
              String s = "";
              while ((s = buffer.readLine()) != null) {
                response += s;
              }
    
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
          return response;
        }
    

    N.B: As DefaultHttpClient is deprecated you can use HttpClientBuilder

提交回复
热议问题