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
Yes you have 3 choices
seperate Thread
.Best choice is AsyncTask. You have to implement your network call
in doInBackground
method of AsyncTask
and 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