2

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

请求是这样的:

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


我正在使用Windows.Web.HttpClient图书馆。

4

1 回答 1

1

通过我在这里找到的示例,我设法解决了我的问题。我用接口
实现了一个新类,并在我的内容上使用了一个。类接口如下所示:IHttpContentJson.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);
于 2014-09-11T17:58:49.247 回答