Cross Platform
Android
iOS

Call a REST Web Service

This recipe shows how call a RESTful service using HTTP, parse Json results and display them in a list.

Recipe



Follow these steps to search Twitter and display the results in a list.

  1. Add a file named TweetItemView.axml under the Resources/layout folder containing the following XML.
<?xml version="1.0" encoding="UTF-8" ?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
 android:padding="15dip"/>
  1. In a ListActivity subclass, add the following code in the OnCreate method to create an HttpWebRequest for a twitter search.
string url = "http://search.twitter.com/search.json?q=xamarin&rpp=10&include_entities=false&result_type=mixed";
var httpReq = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));
  1. Add a reference to System.Json.
  2. Call BeginGetResponse passing it a callback to retrieve the response, and the request.
httpReq.BeginGetResponse ((ar) => {
       var request = (HttpWebRequest)ar.AsyncState;
       using (var response = (HttpWebResponse)request.EndGetResponse (ar))     {                           
              var s = response.GetResponseStream ();
              var j = (JsonObject)JsonObject.Load (s);
              var results = (from result in (JsonArray)j ["results"]
                      let jResult = result as JsonObject
                      select jResult ["text"].ToString ()).ToArray ();
              RunOnUiThread (() => {
                      ListAdapter = new ArrayAdapter<string> (this,
                                  Resource.Layout.TweetItemView, results);
              } );
       }
} , httpReq);

Additional Information

The code uses System.Json to parse the Json results from an HTTP request. The call is asynchronous, so the code to update the UI from the callback is synchronized to the main thread by calling RunOnUiThread.