Xamarin REST communications with ModernHttp

Xamarin and REST go along pretty “easily”.

In this post I will demonstrate how to do that. Our test app will check for stock quotes [1].

Alright, first thing we do is create our Xamarin.Forms project, I usually opt for Shared:

 

We’ll also be targeting Windows Phone 8.1:

 

Adding System.Net.Http to Android and iOS project is as easy as Right click -> Add reference:

 

For WP it’s a little bit different, you need to go to Manage Nuget Packages. I’ve addressed this issue here. You also need to be sure you select Microsoft HTTP Client Libraries and not System.Net.Http as that is a legacy package for WP.

Another important note when we’re targeting WP is that we need to add a reference to System.Windows.Interactivity. For that, just go through the regular process of adding a reference (It’s under Assemblies > Extensions).

Now we want to add some 3rd party libraries! If you chose Shared project remember to add the library to every single project you are targeting!

install-package Newtonsoft.Json
install-package ModernHttpClient

Alright, after that’s out of the way we’ll create a simple app with labels, an entry and a button:

[code lang=”csharp”]public class App : Application
{
public App ()
{
var priceLabel = new Label { HorizontalOptions =
LayoutOptions.CenterAndExpand };
var stockEntry = new Entry
{
Placeholder = "GOOG, AAPL, etc",
HorizontalOptions = LayoutOptions.CenterAndExpand
};
var submitButton = new Button
{
Text = "Check now",
HorizontalOptions = LayoutOptions.CenterAndExpand
};

MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
new Label {
XAlign = TextAlignment.Center,
Text = "Check stock prices for:"
},
stockEntry,
submitButton,
priceLabel
}
}
};
}

//…
}[/code]

Our app looks like this now:

Alright, so now we need to actually implement the REST request:

[code lang=”csharp”]submitButton.Clicked += async (sender, args) =>
{
HttpClient client = new HttpClient(new NativeMessageHandler());
var httpRequest = new HttpRequestMessage(new HttpMethod("GET"),
string.Format("{0}{1}",
"http://www.google.com/finance/info?q=NASDAQ%3a",
stockEntry.Text));

client.Timeout = TimeSpan.FromSeconds(30);

var response = await client.SendAsync(httpRequest);
var jsonString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<GoogleStockData>(
jsonString.Replace("\n// ", "")
.Replace("[", "").Replace("]", ""));

priceLabel.Text = string.Format("Current price for {0} is US$ {1}",
stockEntry.Text,
result.l_cur);
};[/code]

Never mind the JSON replace code, it’s just a quick fix for this tutorial. GoogleStockData is a custom class I created to deserialize the JSON result. With the simple code above we are already making a request using ModernHttpClient, simple as that.

In this line we instantiate the HttpClient using ModernHttpClient:

[code lang=”csharp”]HttpClient client = new HttpClient(new NativeMessageHandler());[/code]

Here we make the actual request:

[code lang=”csharp”]var httpRequest = new HttpRequestMessage(new HttpMethod("GET"),
string.Format("{0}{1}",
"http://www.google.com/finance/info?q=NASDAQ%3a",
stockEntry.Text));[/code]

The remaining lines just deserialize the response. And the final result is this:

That’s it, a simple app that makes a request and handles its response.

[1] The API used in this example is intended for personal use only. Google does not authorize its use if you’re creating an app for public consumption. Be warned!

Project’s GITHUB




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *