Simple REST GET Example using HttpClient

Posted: 2013-07-30 in Windows Phone 8
Tags:

Using Rest with Windows Phone 8

As of Feb 2013 you can now use similar code for both Windows apps and Windows Phone programming when using a RESTFUL service (see here for full details).

 

Assuming you already have a phone app ready to go then all you need to do is (if not run the create your first windows 8 phone app):

1. Use JNuGet to fetch the Http Client package provided by Microsoft. This will give you the System.Net-Http namespace.

Fetch System.Net.Http namespace for windows phone 8

Fetch System.Net.Http namespace for windows phone 8

2. For the UI Add the following to the xaml page for some ui help

<TextBox x:Name="Url" Margin="10,10,0,0" TextWrapping="Wrap" Text="https://www.bitstamp.net/api/ticker/" VerticalAlignment="Top"/>
 <Button x:Name="Go" Content="Go" HorizontalAlignment="Right" Margin="10,82,0,0" VerticalAlignment="Top" Click="Go_Click"/>
 <TextBox x:Name="SpatBack" Margin="10,159,0,0" TextWrapping="Wrap" Text="Nothing so far..."/>

3. In the cs class behind the xaml add the button click event

private async void Go_Click(object sender, RoutedEventArgs e)</code></pre>
{
 var site = Url.Text;
 SpatBack.Text = await Execute(site);
 }

public async Task Execute(string url)
 {
  using(var httpClient = new HttpClient()){
    var request = await httpClient.GetAsync(new Uri(url, UriKind.RelativeOrAbsolute));
    var txt = await request.Content.ReadAsStringAsync();
    return txt;
   }
 }

You’ll need to add a using statement at the top

using System.Net.Http;
using System.Threading.Tasks;

WARNING!!!!!

Do not run the httpclient in the LoadData() in the viewmodel with databinding.
The request will just hang.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s