Forum Cross Platform with Xamarin

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

wallymwallym USInsider, Beta ✭✭✭

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;
    }

Posts

  • SKallSKall USMember ✭✭✭✭

    I prefer to serialize the post from an object, something like this:

                using (var webClient = new WebClient())
                {
                    webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                    // Serializer: object -> string
                    var body = JsonConvert.SerializeObject(post);
                    // POST to server
                    var result = await webClient.UploadStringTaskAsync(uri, body);
                    // Deserializer: string -> object T (possible deser. exception thrown here)
                    var ret = JsonConvert.DeserializeObject<<T>(result);
    
  • wallymwallym USInsider, Beta ✭✭✭

    Thanks @skall. I don't have objects in my current code, just a bunch of data hanging around that I get from multiple sources. I hadn't thought of serializing from an object. I definitely will now. That's a great tip.

  • If you had more calls the ReadAsStringAsyncand Deserialize could be in a generic ProcessResponse<T>. This is an interesting project. It lets you use a rest client over HttpClient. I'm not sure if it works with the Xamarin HttpClient but could be tweaked too.

Sign In or Register to comment.