Skip to content

Instantly share code, notes, and snippets.

@marcoscgdev
Last active July 22, 2019 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcoscgdev/ad9e7d60e59a70825a2c0308350282b3 to your computer and use it in GitHub Desktop.
Save marcoscgdev/ad9e7d60e59a70825a2c0308350282b3 to your computer and use it in GitHub Desktop.
An easy example of background network request in Android using AsyncTask.
package com.marcoscg.sportstv.utils;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class AsyncTaskExample {
public void loadData() {
// Execute the async task
new RestAsyncTask().execute("https://www.google.com/");
}
private class RestAsyncTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Here you can show a progressBar, a loading message...
}
@Override
protected String doInBackground(String... urls) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(urls[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(150000); //milliseconds
httpURLConnection.setConnectTimeout(15000); // milliseconds
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} else {
return "Error: " + httpURLConnection.getResponseCode();
}
} catch (Exception e) {
e.printStackTrace();
return "Error: " + e.getLocalizedMessage();
}
return stringBuilder.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Do whatever you want with the result
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment