如何创建一个 IHttpContent
对象,其中包含 PutAsync
请求正文的内容?
请求是这样的:
IHttpContent myHttpContent = ???
var response = await httpClient.PutAsync(uri, myHttpContent);
我正在使用 Windows.Web.HttpClient
库。
最佳答案
通过样本我找到了here ,我设法解决了我的问题。
我使用 IHttpContent
接口(interface)实现了一个新类,并对我的内容使用了 Json.Parse
。类接口(interface)如下所示:
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);
关于c# - 使用 IHttpContent 发出 HttpClient.PutAsync 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25793560/