2

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.

Schrödinger's Box
  • 3,218
  • 1
  • 30
  • 51
  • 1
    Check the Remarks section on [this page](http://msdn.microsoft.com/library/windows/apps/windows.web.http.ihttpcontent.aspx). – Jason P Sep 11 '14 at 17:27

1 Answers1

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);
Schrödinger's Box
  • 3,218
  • 1
  • 30
  • 51
  • I think this is a good idea, but I would suggest not building json strings manually. At the very least, use the `JavaScriptSerializer` class to convert an anonymous type to a json string. You could also make the `HttpJsonContent` class generic so you can do the parsing inside the class. – Jason P Sep 12 '14 at 15:04
  • You are correct, after a while I arrived at that conclusion. The answer has been updated. – Schrödinger's Box Sep 12 '14 at 16:05