2

I have coded a C# Web Api 2 web service application that uses JSON. I am now wanting to retrieve data from this web service into my Xamarin application.

Here is my Xamarin code:

public AndroidMapCompanyViewModel GetMapCompanyFromWebService(string URL)
{
    AndroidMapCompanyViewModel androidMapCompanyViewModel = new AndroidMapCompanyViewModel ();
    using (var webClient = new System.Net.WebClient()) 
    {

        var json = webClient.DownloadString(URL);
        androidMapCompanyViewModel = JsonConvert.DeserializeObject<AndroidMapCompanyViewModel>(json);
    }
    return androidMapCompanyViewModel;
}

I am getting the following error:

Error: ConnectFailure (Network is unreachable)

With the following URL:

"http://localhost:22101/api/MapCompanyAPI/1"

When clicking on the details for the error, the following is at the top of the list:

System.ArgumentException: Illegal characters in path.

If I open up my browser, I can successfully connect to the URL.

Can I please have some help to de serialize the json data from my localhost url?

Thanks in advance

Simon
  • 7,991
  • 21
  • 83
  • 163
  • Have you setup the permission for your app correctly? Could you try converting your URL to a Uri object and output that to console to see whether there are any issues with characters it can't convert properly? – Frank Aug 08 '14 at 07:09
  • If I place the exact json data into a text file and place this on an http web server of mine, my app retrieves the data with no errors. The error must be related to just using my localhost. – Simon Aug 08 '14 at 08:58
  • Just checking, but you are running this WebService on the same SmartPhone as you're running this Xamarin code? – Frank Aug 08 '14 at 09:02
  • I have the web service running in VS2013, on the default localhost. – Simon Aug 08 '14 at 09:21
  • Oh, that will be why... The cell phone cannot see my localhost can it. – Simon Aug 08 '14 at 09:22

1 Answers1

0

Apparently you're using localhost to refer to your desktop machine. Here's how you connect your Android device to your desktop's localhost.

android connect to PC's localhost when debugger on mobile device

Additionally it's probably better to use HttpClient instead of WebClient. Here's an example using HttpClient I just cobbled together.

public void DownloadJson ()
{
    using (var httpClient = new HttpClient ())
    {
        var response = httpClient.GetAsync (URL).Result;

        if (response.IsSuccessStatusCode) {
            var responseContent = response.Content;
            string contents = responseContent.ReadAsStringAsync ().Result;

            // insert your code here
        }
    }
}
Community
  • 1
  • 1
Frank
  • 733
  • 5
  • 7
  • Frank, can you explain the difference between using HttpClient instead of WebClient? – Simon Aug 08 '14 at 09:24
  • http://stackoverflow.com/questions/20530152/need-help-deciding-between-httpclient-and-webclient – Frank Aug 08 '14 at 09:33