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

jon*_*nes 3 c# asynchronous httpclient

我正在尝试从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");
Run Code Online (Sandbox Code Playgroud)

发送消息:

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

使用此代码,我可以获取状态代码和一些标头信息,但无法获取响应本身。我也尝试过:

  HttpResponseMessage response = await client.SendAsync(sendRequest);
Run Code Online (Sandbox Code Playgroud)

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

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

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

Hak*_*tık 5

这是一种使用方法HttpClient,如果请求返回状态为200(请求不是BadRequestNotAuthorized),它应该读取请求的响应。

string url = 'your url here';

using (HttpClient client = new HttpClient())
{
     using (HttpResponseMessage response = client.GetAsync(url).Result)
     {
          using (HttpContent content = response.Content)
          {
              var json = content.ReadAsStringAsync().Result;
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

有关完整的详细信息,以及如何async/awaitHttpClient您一起使用,请阅读此答案的详细信息

  • @FrijeyLabs实际上我想感谢你让我注意到这个问题,调用“同步优于异步”是不好的,它可能会导致死锁。我已经更新了我的答案以使用最佳实践。请再看一遍答案。 (2认同)