Make a HttpClient.PutAsync request with IHttpContent

How can I create an IHttpContent object with content to PutAsync request body?

The request is like this:

IHttpContent myHttpContent = ???
var response = await httpClient.PutAsync(uri, myHttpContent);


I'm using the Windows.Web.HttpClient library.

Upvotes: 2

Views: 3797

Answers (1)

Through the sample I found here, I managed to solve my problem.
I implemented a new class with the IHttpContent interface and used a Json.Parse on my content. The class interface looks like this:

    public class HttpJsonContent : IHttpContent {
        IJsonValue jsonValue;
        HttpContentHeaderCollection headers;

        public HttpContentHeaderCollection Headers {
            get { return headers; }
        }

        public HttpJsonContent(IJsonValue jsonValue) {
            if (jsonValue == null) {
                throw new ArgumentException("jsonValue cannot be null.");
            }

            this.jsonValue = jsonValue;
            headers = new HttpContentHeaderCollection();
            headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
            headers.ContentType.CharSet = "UTF-8";
        }
    ...


And my request like this:

// Optionally, define HTTP Headers
httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json");

JsonObject jsonObj = new JsonObject();
jsonObj["content_one"] = JsonValue.CreateNumberValue(600);
jsonObj["content_two"] = JsonValue.CreateStringValue("my content value");

// Create the IHttpContent
IHttpContent jsonContent = new HttpJsonContent(jsonObj);

// Make the call
HttpResponseMessage response = await httpClient.PutAsync(uri, jsonContent);

Upvotes: 1

Related Questions