7

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.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
jones
  • 585
  • 3
  • 10
  • 30
  • 1
    There is no wrong or right way to do this. Depending on your application, both make sense. If you are not sure, i would personally recommend the async/await approach. – Thomas D. Jan 20 '17 at 11:49
  • There's no way to have all the code inside the constructor I suppose? I'm just testing out an api at the moment. – jones Jan 20 '17 at 12:12
  • I am not sure what the problem with the mentioned solutions is, but you can also just use the Result Property. var response = client.SendAsync(sendRequest).Result; Note that you "lose" the asynchrony with this approach. This is blocking (like await). – Thomas D. Jan 20 '17 at 12:20
  • 1
    Solution is fine , just tried to print result in constructor instead of having to create async methods, this seemed to do the trick : `HttpResponseMessage response = client.SendAsync(sendRequest).Result; ` `var result = response.Content.ReadAsStringAsync().Result;` – jones Jan 20 '17 at 12:46
  • I still don't know what constructor you are talking about. Glad you got it working anyways ;) – Thomas D. Jan 20 '17 at 12:47
  • I meant inside the `public Form1() { } `, the code that is initially ran when i start my program, i apologize if im using the wrong terms here, still a c# beginner – jones Jan 20 '17 at 12:50

1 Answers1

18

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 = client.GetAsync(url).GetAwaiter().GetResult())
{
    using (HttpContent content = response.Content)
    {
         var json = content.ReadAsStringAsync().GetAwaiter().GetResult();
    }
}

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

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131