Android Code to Access Web Services

Android Code to Access Web Services
Page content

Nowadays mobile devices give us the chance to be connected to the Internet everywhere if we have access to a mobile network, everyone can write a tweet in the subway, or check their email while sitting on the beach. But, as a developer, how can I create an application in Android that has access to the web and can retrieve some data from it? And once the information is retrieved, how can I treat it? How can I show it in my application? Do I have to use a background process? Or do I have to access the Internet using the main UI thread?

For accessing the Internet on our Android device, we are going to use the Apache HTTP API, it’s an easy and very well known API, that is included in the Android API. The data retrieved from the web has a JSON format so we are going to use the GSON library, it’s an easy and very quick way to parse JSON data and convert it to a Java object. And we are going to see the differences between accessing the Internet using a background process (AsyncTask in this case) or accessing in the main UI thread.

During a series of articles I will be answering these questions, showing source code and detailing my own experience. Let’s start with the base… how do we access the web?

Code to Access Web

For this example (you will find the full source code at the end of the article) I will create a class that manages all the web access so once it’s built we don’t have to bother about how it works anymore, we use it as an external API.

This is how we will use the class:

BasicWebService webService = new BasicWebService(webURL);

String response = webService.webGet();

We instantiate the class BasicWebService (home made class) passing as input value the URL we want to connect, and using the webGet method of this class, we get the response (as a string).

Fine, but we are interested in how BasicWebService class works. Let’s check it:

public BasicWebService(String serviceName){

HttpParams myParams = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(myParams, 10000);

httpClient = new DefaultHttpClient();

webServiceUrl = serviceName;

}

This is the constructor, we receive as an input value the web URL we want to access. Inside the constructor we initialize the classes we are going to use: The defaultHttpClient, we set a set of parameters (timeout parameters in this case, after 10000 milliseconds we get a timeout if the service doesn’t give a response) and we set a variable to store the service name (the URL as a string).

The webGet method is implemented as follows:

public String webGet() {

httpGet = new HttpGet(webServiceUrl);

try {

response = httpClient.execute(httpGet);

returnedValue = EntityUtils.toString(response.getEntity());

} catch (IOException e) {

Log.e(“WebService:”, " Messaje " + e.getMessage());

} catch (Exception e) {

Log.e(“WebService:”, " Messaje " + e.getMessage());

}

return returnedValue;

}

Hint! All the objects you see here are declared at the top of the class, I have not place the code here because it’s redundant. To see the full source code, you can go to the end of the article.

With the HttpGet class we specify that we want to use a GET request to the server. The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. Inside the Try-catch code snippet, we call the execute method from the DefaultHttpClient object, passing the httpGet object as a parameter. This way, we retrieve the response, we convert it to a string. The Entity is a generic stream that has been received in the connection.

So, we return the string we have just received from the server. This string, in this case, is a JSON, but it can be anything you can get as a response from a server, plain text, html, xml, compressed data….

A basic JSON text has the following structure:

{“id”:“20”,“text”:“Hi!BrightHub”,“date”:“2011-05-14 23:02:54”}

It’s like a key:value array structure in plain text.

But, how can we treat this string in Android? How do we show that info in our application? Let’s talk about it in the next article.

References

This post is part of the series: Android Code to Access the Web

With this series of articles I will show Android developers a code example to connect your Android device to the Internet, retrieve data from it and treat that information. Using the right background process in Android is explained too.

  1. Android App Development: How to Access the Internet and Retrieve Info with Your App
  2. Android Development: GSON library and JSON Strings
  3. Android Development: Background Process for a Heavy Task