gpt4 book ai didi

c# - 如何从 Httpclient.SendAsync 调用获取和打印响应

转载 作者:行者123 更新时间:2023-11-30 14:48:25 30 4
gpt4 key购买 nike

我正在尝试从 HTTP 请求中获取响应,但我似乎做不到。我尝试了以下方法:

public Form1() {     

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("someUrl");
string content = "someJsonString";
HttpRequestMessage sendRequest = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
sendRequest.Content = new StringContent(content,
Encoding.UTF8,
"application/json");

发送消息:

    ...
client.SendAsync(sendRequest).ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
} // end public Form1()

使用这段代码,我得到了状态代码和一些 header 信息,但我没有得到响应本身。我也试过:

  HttpResponseMessage response = await client.SendAsync(sendRequest);

但我被告知要创建一个如下所示的异步方法以使其工作

private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
HttpResponseMessage response = await client.SendAsync(msg);
string rep = await response.Content.ReadAsStringAsync();
}

这是发送“HttpRequest”、获取并打印响应的首选方式吗?我不确定哪种方法是正确的。

最佳答案

这里有一种使用HttpClient的方法,这应该读取请求的响应,以防请求返回状态200,(请求不是BadRequest或者未授权)

string url = 'your url here';

// usually you create on HttpClient per Application (it is the best practice)
HttpClient client = new HttpClient();

using (HttpResponseMessage response = client.GetAsync(url).GetAwaiter().GetResult())
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}

有关完整的详细信息以及如何将 async/awaitHttpClient 一起使用,您可以阅读 this answer 的详细信息

关于c# - 如何从 Httpclient.SendAsync 调用获取和打印响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41762947/

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