本文介绍了如何从Httpclient.SendAsync调用获取和打印响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从HTTP请求中获取响应,但是我似乎无法.我尝试了以下方法:

I'm trying to get a response from a HTTP request but i seem to be unable to. I have tried the following:

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");

通过以下方式发送消息:

Send message with:

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

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

With this code, i get back the status code and some header info, but i do not get back the response itself. I have tried also:

  HttpResponseMessage response = await client.SendAsync(sendRequest);

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

but I'm then told to create a async method like the following to make it work

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

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

Is this the preferred way to send a 'HttpRequest', obtain and print the response? I'm unsure what method is the right one.

推荐答案

这是使用HttpClient的方法,在请求返回状态为200的情况下,它应该读取请求的响应((请求不是) BadRequestNotAuthorized)

here is a way to use HttpClient, and this should read the response of the request, in case the request return status 200, (the request is not BadRequest or NotAuthorized)

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结合使用,您可以阅读此答案的详细信息

and for full details and to see how to use async/await with HttpClient you could read the details of this answer

这篇关于如何从Httpclient.SendAsync调用获取和打印响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 08:55