Search code examples
windows-phone-7dotnet-httpclientprinter-control-language

Getting Windows Phone and HttpClient PCL working


I'm trying to use the new HttpClient PCL in a Windows Phone 7.1 project. The project is using Microsoft.Net.Http 2.1.3-beta from NuGet.

Code:

var client = new HttpClient();
client.BaseAddress = new Uri("http://api.geonames.org/");
var resp = client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt").Result;
var earthquakesJson = resp.Content.ReadAsStringAsync().Result;

This code works fine in a Windows Forms application.

When debugging the application just stops working on method HttpClient.GetAsync (on emulator or device). Internet is working on device/emulator.

Steps to reproduce:

. create Windows Phone 7.1 app (file -> new -> project)

. nuget command: 'install-package microsoft.net.http -pre'

. add code above to MainPage

How can I get this working?


Solution

  • To fix your problem do the following:

    Install the Microsoft Async for WP7.1: install-package microsoft.Bcl.Async

    Change your code to:

    private async void GetData() {
       var client = new HttpClient();
    
       client.BaseAddress = new Uri("http://api.geonames.org/");
       var earthquakesJson = await client.GetStringAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt");
       ...      
    }