Search code examples
c#asynchronoushttpclient

How to get and print response from Httpclient.SendAsync call


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.


Solution

  • 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';
    
    // usually you create on HttpClient per Application (it is the best practice)
    HttpClient client = new HttpClient();
    
    using (HttpResponseMessage response = await client.GetAsync(url))
    {
        using (HttpContent content = response.Content)
        {
             var json = await content.ReadAsStringAsync();
        }
    }
    

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