Search code examples
restxamarin.formsgethttpwebrequest

Xamarin forms Http web request


I'm working on a Xamarin.Forms project and in the project I have to GET data from a Json URL, I'm using this code :

 string URL = "https://example.com/.json";
   var httprequest = (HttpWebRequest)WebRequest.Create(URL);
   var response = (HttpWebResponse)httprequest.GetResponse();
   var stream = new StreamReader(response.GetResponseStream()).ReadToEnd();
   var firebasevariable = JObject.Parse(stream);
   string dist = firebasevariable["distance"].ToObject<string>();

but the "dist" value keeps returning NULL ! I imported the System.Net.Http and the Newtonsoft.Json libraries I also get this warning but I don't know if its the cuz why I get the NULL , I tried my link using the postman and it returns the data perfectly

There was a conflict between "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" and "mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"


Solution

  • I'm using Firebase too and this is working:

    async Task<string> Get(string url)
    {
        using(var requestMessage = new HttpRequestMessage(HttpMethod.Get, url))
        {
            // Client is a static HttpClient property. 
            // It's recommended to use a single instance in all your requests, but create it in this method if you want.
            var response = await Client.SendAsync(requestMessage);
    
            var contentString = await response.Content.ReadAsStringAsync();
    
            if (response.IsSuccessStatusCode)
                return contentString;
            else
                throw new Exception(contentString);
        }
    }
    

    This method will, of course, return a JSON string. After getting it, you can deserialize it to whatever you want.

    If the exception is thrown, it probably means authentication issues (just read what contentString says). If it returns correctly but the value is null, then probably you are using a different URL from your Postman tests and the path's value on the database is really null.

    Hope it helps!