Android REST Communication

Android REST Communication

Introduction

Mobile devices are getting popular and many people are carrying a mobile device with Internet connectivity in their pockets. Designing a scalable solution to allow these devices to communicate to a central server to perform operation is a becoming necessary for businesses and organizations.
The Android-JBridge project is an open source mobile to server implantation which allows Android mobile devices to connect to the web services on the central server.

This project is deployed on Google Code and can be accessed at: Android JBridge

The source code for both mobile client and server are accessible in there as well as the compiled EAR file to be deployed under the JBoss application server.
This project demonstrates on how to connect to the REST web services from the Android client to insert, update, select or delete resources in the web server. This project uses JBoss 4.x for the application server with RESTEasy 2 framework from the JBoss community with Android SDK which runs on the Android OS 2.2 and higher.

Retrieving data via REST

To retrieve data from the REST web services, Products activity sends a request to the doGet method in the RestEasy class by passing the products web services URI and this function opens a httpGet request to the products method in the RESTEasy to get the JSON formatted data by adding accept “application/json” header to the request:

public static JSONObject doGet(String url) {
    JSONObject json = null;
    HttpClient httpclient = new DefaultHttpClient();
    // Prepare a request object
    HttpGet httpget = new HttpGet(url);
    // Accept JSON
    httpget.addHeader("accept", "application/json");
    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Get the response entity
        HttpEntity entity = response.getEntity();
        // If response entity is not null
        if (entity != null) {
            // get entity contents and convert it to string
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            // construct a JSON object with result
            json=new JSONObject(result);
            // Closing the input stream will trigger connection release
            instream.close();
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // Return the json
    return json;
}

Inserting data via REST

To insert a new record in the JBoss database or adding a new resource, doPost method is used in the RESTEasy class. It is possible to use doPut as well, however to demonstrating Post method, in this implantation we have used doPost for insert and doPut for update purpose:

public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        StringEntity s = new StringEntity(c.toString());

        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");

        request.setEntity(s);
        request.addHeader("accept", "application/json");

        return httpclient.execute(request);
}

Updating data via REST

To update an existing record, doPut option is being used which in this example, we will reduce the product quantity after user clicks on the buy button:

public static HttpResponse doPut(String url, JSONObject c) throws ClientProtocolException, IOException
{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPut request = new HttpPut(url);
        StringEntity s = new StringEntity(c.toString());
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");

        request.setEntity(s);
        request.addHeader("accept", "application/json");

        return httpclient.execute(request);
}

Delete records via REST

To delete a product from the database, doDelete method in the RestEasy class is being used. Similar to the doPut method, this method connects to the RESTEasy web services providing the id number in the URL , for example to delete a product with product id of 1 we can pass: http://127.0.0.1/JBridge/product/1/delete. Following method defines doDelete method in the Android RestEasy class:

public static void doDelete(String url) throws  ClientProtocolException, IOException{
    	HttpClient httpclient = new DefaultHttpClient();
    	HttpDelete delete = new HttpDelete(url);
    	delete.addHeader("accept", "application/json");
    	httpclient.execute(delete);
}

JBoss Application Server

The server application consist of entity beans, session beans, servlets, web pages and REST web services. Entity beans are our entity classes such as Product which will be mapped to the database tables as well. Session beans are the core components to perform operations to store and retrieve the data from database and act as a bridge between our REST web services and the database. The servlet provides operations between web pages and our session beans. So it handles requests and responses made from web pages in the JBoss. REST web services are implemented to accept requests from our mobile client and connect to the session beans to pass the queries and return the results from session beans.

Android REST
The server application which includes a servlet and web page GUI which allows developers to perform testing, however the key components of this project lies under Android client and RestEasy web services. The servlet and web layout will be accessible via following URL:

http://127.0.0.1:8080/JBridge/Shop

JBoss application server will run on the server and depending on the project scale can be clustered to run on multiple servers to provide better performance.

One of the features of RESTEasy is supporting JSON (JavaScript Object Notation) which is a lightweight standard designed data interchange. Data transfer between mobile client and server will be in form of JSON which is a new concept in this prototype and can be evaluated by comparing to the other data types. In the RESTEasy web services in this project both JSON and XML annotations uses for the data retrieval purposes which enables the system to support both data types. By default the web service returns XML data type unless it is defined in the header to return JSON data. The reason is that XML data type is more human readable than JSON and it helps for testing and development purposes by visiting the REST resources URIs to view XML data. In our Android client, we use Accept JSON header to make sure that we get JSON data type from the web services.

About majid

Software engineer, Web developer and IT graduate. Profile: View My Profile
This entry was posted in Mobile Programming, Tutorials. Bookmark the permalink.