如何创建包含IHttpContent
请求正文内容的PutAsync
对象?
请求是这样的:
IHttpContent myHttpContent = ???
var response = await httpClient.PutAsync(uri, myHttpContent);
我正在使用Windows.Web.HttpClient
库。
答案 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);