[c#] How to send a Post body in the HttpClient request in Windows Phone 8?

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 peice of code so that if there is any post body data it gets added in the request that I make and if its simple GET or POST without body it send the request that way. Please update the code below:

HttpClient client = new HttpClient();

// Add a new Request Message
HttpRequestMessage requestMessage = new HttpRequestMessage(RequestHTTPMethod, ToString());

// Add our custom headers
if (RequestHeader != null)
{
    foreach (var item in RequestHeader)
    {

        requestMessage.Headers.Add(item.Key, item.Value);

    }
}

// Add request body


// Send the request to the server
HttpResponseMessage response = await client.SendAsync(requestMessage);

// Get the response
responseString = await response.Content.ReadAsStringAsync();

This question is related to c# windows-phone-8 httpclient

The answer is


This depends on what content do you have. You need to initialize your requestMessage.Content property with new HttpContent. For example:

...
// Add request body
if (isPostRequest)
{
    requestMessage.Content = new ByteArrayContent(content);
}
...

where content is your encoded content. You also should include correct Content-type header.

UPDATE:

Oh, it can be even nicer (from this answer):

requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");

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<string, string> 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<T>(string httpMethod, string route, Dictionary<string, string> 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<T>(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<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to windows-phone-8

Microsoft Advertising SDK doesn't deliverer ads Calling async method on button click How to send a Post body in the HttpClient request in Windows Phone 8? Call asynchronous method in constructor? Install Visual Studio 2013 on Windows 7 How to post data using HttpClient? How to upload file to server with HTTP POST multipart/form-data? DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371" How to Deserialize JSON data? How to Install Windows Phone 8 SDK on Windows 7

Examples related to httpclient

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M? PHP GuzzleHttp. How to make a post request with params? C#: HttpClient with POST parameters How to send a Post body in the HttpClient request in Windows Phone 8? The type List is not generic; it cannot be parameterized with arguments [HTTPClient] How to add,set and get Header in request of HttpClient? No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain' SSL "Peer Not Authenticated" error with HttpClient 4.1 Apache HttpClient Interim Error: NoHttpResponseException Common HTTPclient and proxy