Sunday, August 12, 2012

REST with JSON - part 1

In this entry of the blog I want to explain how to consume RESTful web services from an Android application using the format JSON for the information.

The term REST stands for Representational State Transfer. REST is not a technology, and many tools available on the market might not support REST directly because of the lack of a specific standard. What makes REST the best choice in many scenarios, is its ease of implementation and the fact that REST is not tied to any particular system, language or tool. If you can send an HTTP request to a web server, you can use REST.

To define what should be done on a specific resource, REST uses the intrinsic meaning of the verbs of the http protocol. Here are the five main verbs that are commonly used in RESTful systems:
  • GET - Retrieve a resource
  • PUT - Create a resource
  • POST - Update a resource
  • DELETE - Delete a resource
  • HEAD - Retrieve the metadata that defines a resource

If we don't want to create our REST service in a web/application server we can use one of the thousands of services available on the Internet. For instance Twitter.

To retrieve the user timeline of  Joel Comm the author of the book Twitter Power, we can access the uri:
http://twitter.com/statuses/user_timeline/joelcomm.json

And it will return the user timeline in JSON format. You can try it in your browser. If you are using Firefox there is a tool called RESTClient that helps you viewing the information of the REST services.

Of course Twitter has much more resources published. You can see them here.
Some of the resources are not accessible without authentication, but in this part we are going to use only resources that don't need authentication.

To make this in android we need to have an application with INTERNET permission. In the manifest:
<uses-permission android:name="android.permission.INTERNET"/>

This application has to create a Http Get method, execute it and get the response. The information will be in a HttpEntity object.

                
StringBUilder sBuffer = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
  HttpGet hget = new HttpGet(URI);
  hget.addHeader("accept", FORMAT);
  
  try {
   HttpResponse response = httpClient.execute(hget);
   StatusLine statusLine = response.getStatusLine();
   if (statusLine.getStatusCode() == 200){
    //deal with the entity
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    BufferedReader bReader = new BufferedReader(new InputStreamReader(content));
    String line;
    while((line = bReader.readLine()) != null)
     sBuffer.append(line);
    
   }
   else{
    Log.e(TAG,"Error downloading data ");
    
   }
   
  } catch (ClientProtocolException e) {
   Log.e(TAG, "Error client protocol bad");
   e.printStackTrace();
   
   
  } catch (IOException e) {
   Log.e(TAG, "Error io execption");
   e.printStackTrace();
   
  }
  
  String resultInJsonFormat = sBuffer.toString();
 

To extract the information from the Entity we can use alternatively the toString(HttpEntity) method of EntityUtils

String resultInJsonFormat = EntityUtils.toString(entity);

As you know, if you get information from the Internet, it could be a little slow. So you shouldn't use the User Interface thread to do this kind of things because while is downloading information the UI will remain blocked (and it doesn't likes to the users). But we'll see how to do that in a further entry...

Now that we have the information in JSON format let's see what's that. Wikipedia says that JSON , or JavaScript Object Notation, is a text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages.

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

Note that the information could come as a JSON Object or as a JSON Array. In this concrete case is a JSONArray.  To parse this formats in Java we have the package org.json.* and is easy to use. Let's see the simple code:


JSONArray jsonArray = new JSONArray(jsonRaw);
   int length = jsonArray.length();
   builder.append("Length: "+length+"\n");
   JSONObject jObject;
   for(int i=0; i < length;i++ ){
    jObject = jsonArray.getJSONObject(i);
    builder.append(jObject.getString("text")+"\n");
   }

In this case we are getting the String from the field text of each JSONObject in the array. There are lots of fields in each object.

Well that's a simple example of using REST and JSON in android. In further entries we'll see how to authenticate.

No comments:

Post a Comment