gpt4 book ai didi

c# - 使用 IHttpContent 发出 HttpClient.PutAsync 请求

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:49 25 4
gpt4 key购买 nike

如何创建一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com