In mobiles applications, very often you should get data from a Web Service to update content displayed to users. For example, you can imagine a weather application that needs to request weather data from a remote server. Content getted can be under different formats but JSON format is one of the most used format with REST Web Service.

So, you’re going to learn how to consume a REST Web Service and how to parse JSON result to update an Android application.

1. Consume a REST Web Service

First, we need to select a REST Web Service to consume. Here, we choose to consume a Web Service provided by Youtube API. It lets developers to request for a list of videos URLs by entering a query. You can try the Web Service response by requesting the following URL :

http://gdata.youtube.com/feeds/api/videos?q=Android&v=2&max-results=20&alt=jsonc&hl=en

Here, you can note the following parameters :

  • q to enter query
  • v to select version of API
  • max-results to limit the number of results
  • alt to define the response format
  • hl to define language of the response

JSON format of the response will be important in step 2 when you will parse result to get data.

web_service_youtube_video
To consume the REST Web Service, you’re going to use HttpClient API provided in standard by SDK Android. Client is designed thanks to HttpClient interface where as HTTP methods are designed thanks to HttpGet and HttpPost classes. A HTTP response is designed thanks to interface HttpResponse.

Here, you wanna make an Http Get request, so code will be like that :


public String requestContent(String url) {
  HttpClient httpclient = new DefaultHttpClient();
  String result = null;
  HttpGet httpget = new HttpGet(url);
  HttpResponse response = null;
  InputStream instream = null;

  try {
    response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
      instream = entity.getContent();
      result = convertStreamToString(instream);
    }

  } catch (Exception e) {
    // manage exceptions
  } finally {
    if (instream != null) {
      try {
        instream.close();
      } catch (Exception exc) {

      }
    }
  }

  return result;
}

public String convertStreamToString(InputStream is) {
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  StringBuilder sb = new StringBuilder();
  String line = null;

  try {
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
  } catch (IOException e) {
  } finally {
    try {
      is.close();
    } catch (IOException e) {
    }
  }

  return sb.toString();
}

Content is read line by line via an InputStream instance. All is setted in a String that is called result of the Web Service call.

 

2. Parse JSON result

Now, you can get JSON data from Youtube by entering a query thanks to requestContent() method. Following step is to parse JSON result to manage content and update your application.

Data about videos will be stored in Video objects. A Video class is a simple POJO :


public class Video {

  private String title;
  private String description;
  private String link;
  private String picture;

  public Video(){
  }

  public Video(String title, String description, String link, String picture){
    this.title = title;
    this.description = description;
    this.link = link;
    this.picture = picture;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public String getLink() {
    return link;
  }

  public void setLink(String link) {
    this.link = link;
  }

  public String getPicture() {
    return picture;
  }

  public void setPicture(String picture) {
    this.picture = picture;
  }

}

To parse the JSON content, you can use JSON standard API provided by Android SDK. All the APIs turn around 2 classes : JSONObject an JSONArray. Code to parse the content is here :


 ArrayList<Video> videos = new ArrayList<Video>();

 try {
   JSONObject json = new JSONObject(res);
   JSONObject dataObject = json.getJSONObject("data");
   JSONArray items = dataObject.getJSONArray("items");

   for (int i = 0; i < items.length(); i++) {
     JSONObject videoObject = items.getJSONObject(i);
     Video video = new Video(videoObject.getString("title"),
                             videoObject.getString("description"),
                             videoObject.getJSONObject("player")
                                        .getString("default"),
                             videoObject.getJSONObject("thumbnail")
                                        .getString("sqDefault"));
     videos.add(video);
   }

 } catch (JSONException e) {
   // manage exceptions
 }

When parsing is done, you get a list of videos objects containing all the data you need for your application.

 

3. Use an Asynchronous Task to call Web Service

With a method to consume Web Service and other to parse JSON result, we must assemble all inside an asynchronous task that will proceed the call without blocking UI main thread. To achieve that, you can use an AsyncTask implementation like this :


private static final String URL = "http://gdata.youtube.com/feeds/api/videos?q=$QUERY$&v=2&max-results=20&alt=jsonc&hl=en";

// ...

new AsyncTask<String, Void, String>() {
  @Override
  protected void onPreExecute() {
    mDialog = ProgressDialog.show(MainActivity.this,
      "Load in progress", "Wait ...", true, true);
  }

  @Override
  protected String doInBackground(String... params) {
    String realUrl = URL.replace("$QUERY$", "Android");
    return requestContent(realUrl);
  }

  @Override
  protected void onPostExecute(String res) {
    videos = new ArrayList<Video>();

    try {
      JSONObject json = new JSONObject(res);
      JSONObject dataObject = json.getJSONObject("data");
      JSONArray items = dataObject.getJSONArray("items");

      for (int i = 0; i < items.length(); i++) {
        JSONObject videoObject = items.getJSONObject(i);
        Video video = new Video(videoObject.getString("title"),
                                videoObject.getString("description"),
                                videoObject.getJSONObject("player")
                                           .getString("default"),
                                videoObject.getJSONObject("thumbnail")
                                           .getString("sqDefault"));

        videos.add(video);
      }

    } catch (JSONException e) {
      // manage exceptions
    }

    mVideosAdapter = new VideosListAdapter(MainActivity.this, videos);
    mVideosLv.setAdapter(mVideosAdapter);
    // dismiss progress dialog
    Utils.dismissDialog(mDialog);
  }

}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // we target SDK > API 11

In onPreExecute() method, you could display a progress dialog to warn user that load is in progress. It’s good because this method is called in UI main thread. The Web Service call is made in doInBackground method which is called in a separated thread. Then, in onPostExecute() method, you get result from Web Service load and parse JSON. Note that for big object to parse, you could also put the parsing in doInBackground() method.

When list of videos is filled, you could choose to display data in a specific ListView widget in your application thanks to a VideosListAdapter.

 

4. Application demo

Like said previously, the main part of the job is done and you must just create a simple UI to display data loaded. Result should be like that :

web_service_sample_screenshot