如何从Httpclient.SendAsync调用

时间:2017-01-20 11:46:11

标签: 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");

发送消息:

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

使用此代码,我会返回状态代码和一些标题信息,但我不会自己回复响应。我也试过了:

  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();
}

这是发送&#39; HttpRequest&#39;的首选方式,获取并打印回复?我不确定哪种方法是正确的。

1 个答案:

答案 0 :(得分:2)

这是一种使用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;
          }
     }
}

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

的详细信息