AsyncTask in Java and doing HTTP calls


Most HTTP or REST API calls are done asynchronously. In Java, that means having to make use of the AsyncTask class to execute such calls. You can do a HTTP protocol based call inside of a class that extends the AsyncTask class.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

Here’s a simple example of creating and using a class that uses AsyncTask. What this code does is take a URL passed in, does some HTTP based calls, and returns all of the text inside the paragraph HTML tag using a library called JSoup.

//using our AsyncTask object to get text from a website
 private void getTextFromURL(String originalText)
{
        String testString = originalText;
    	boolean isUrl = isValidURL(originalText);
	URLParser uparse = new URLParser();
	AsyncTask<String, Void, String> asyncTask = null;
    	if(isUrl) //is the string entered a valid url?
    	{   
            //if so, call on asyncTask with URLParser to execute the method
    	    asyncTask = uparse.execute(testString);
    	}
    	try
	{
                //if our asyncTask was successful, lets get the text
		originalText = asyncTask.get();
	} catch (InterruptedException e1)
	{
		e1.printStackTrace();
	} catch (ExecutionException e1)
	{
		e1.printStackTrace();
	}
}
//lets check if the string entered is a valid URL
public static boolean isValidURL(String urlString)
	{
	    try
	    {
	        URL url = new URL(urlString);
	        url.toURI();
	        return true;
	    } 
	    catch (Exception exception)
	    {
	        return false;
	    }
	}


public class URLParser extends AsyncTask<String, Void, String>
    {
    	Document doc = null;
		org.jsoup.Connection.Response response = null;
		org.jsoup.Connection connection = null;
		String originalText = null;
		public URLParser()
		{
		}
		@Override
		protected String doInBackground(String... params)
		{
			String testString = params[0];
			try
			{
				URLEncoder.encode(testString, "UTF-8") ;
			} catch (UnsupportedEncodingException e2)
			{
				e2.printStackTrace();
			}
			try
			{
				response = Jsoup.connect(testString)
                        .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
                        .timeout(5000)
                        .execute();
				if(response.statusCode() == 200)
				{
					connection = Jsoup.connect(testString);
					doc = connection.ignoreContentType(true).get();
				}
				else
				{
					Toast.makeText(getApplicationContext(), "Error retrieving from the URL!", Toast.LENGTH_LONG).show();
				}
			} 
			catch (IOException e1)
			{
				e1.printStackTrace();
			}
    		Elements allParagraphText = doc.select("p");
    		originalText = allParagraphText.text();
    		return originalText;
		}
    	@Override
    	protected void onPostExecute(String result)
    	{
    		super.onPostExecute(result);
    	}
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s