Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Calling JSON Endpoint (Web API) with HttpClient and async/await - Need suggestions

$
0
0

I'm starting to integrate the async/await with the httpclient into my code and converting from the async begin/end pattern. I'm doing 100% posts (sorry Restofarians :-) ). I've got the code below for returning a list of provinces in a country. does this look good for performing a post? Any additional suggestions or anything I can do to improve what I am doing? I'm creating some data to post, creating my httpclient instance, posting it, getting some data back as a string, and then deserializing it using json.net. Should I be doing something else? Can I improve this? Any suggestions are appreciated.

Wally

    async public Task<List<CallWebServices.Province>> ProvincesBegin(Int64 CountryID)
    {
        string json;
        string Url = WebEndpoints.ProvinceEndPoint ();
        List<CallWebServices.Province> prov = new List<Province> ();
        try
        {
            var postData = new List<KeyValuePair<string, string>>();
            postData.Add(new KeyValuePair<string, string>("AppKey", Settings.AppKey));
            postData.Add(new KeyValuePair<string, string>("CountryID", CountryID.ToString()));
            HttpContent content = new FormUrlEncodedContent(postData);

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            var result = client.PostAsync(Url, content);
            json = await result.Result.Content.ReadAsStringAsync();
            prov = JsonConvert.DeserializeObject<List<Province>>(json);
        }
        catch(System.Exception sysExc)
        {
            Console.WriteLine("Exception: {0}", sysExc);
            throw;
        }
        return prov;
    }

Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>