How to get and print response from Httpclient.Send

2019-05-26 09:55发布

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

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

1条回答
可以哭但决不认输i
2楼-- · 2019-05-26 10:35

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

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

查看更多
登录 后发表回答