How to send a Post body in the HttpClient request in Windows Phone 8?

后端 未结 2 1676
广开言路
广开言路 2020-12-24 04:55

I have written the code below to send headers, post parameters. The problem is that I am using SendAsync since my request can be GET or POST. How can I add POST Body to this

2条回答
  •  攒了一身酷
    2020-12-24 05:17

    I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

    Generic method to call the API:

        private static T MakeRequest(string httpMethod, string route, Dictionary postParams = null)
        {
            using (var client = new HttpClient())
            {
                HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
    
                if (postParams != null)
                    requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body
    
    
                HttpResponseMessage response = client.SendAsync(requestMessage).Result;
    
                string apiResponse = response.Content.ReadAsStringAsync().Result;
                try
                {
                    // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                    if (apiResponse != "")
                        return JsonConvert.DeserializeObject(apiResponse);
                    else
                        throw new Exception();
                }
                catch (Exception ex)
                {
                    throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
                }
            }
        }
    

    Call the method:

        public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
        { 
            // Here you create your parameters to be added to the request content
            var postParams = new Dictionary { { "cardNumber", cardNumber }, { "country", country } };
            // make a POST request to the "cards" endpoint and pass in the parameters
            return MakeRequest("POST", "cards", postParams);
        }
    

提交回复
热议问题