Android: AsyncTask to make an HTTP GET Request?
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
}
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) {
}