使用IHttpContent创建HttpClient.PutAsync请求

时间:2014-09-11 17:23:35

标签: c# httprequest httpclient put httpcontent

如何创建包含IHttpContent请求正文内容的PutAsync对象?

请求是这样的:

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


我正在使用Windows.Web.HttpClient库。

1 个答案:

答案 0 :(得分:1)

通过我找到here的样本,我设法解决了我的问题 我使用IHttpContent界面实现了一个新类,并在我的内容上使用了Json.Parse。类接口如下所示:

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


我的要求是这样的:

// 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);