0

I have the following code as a start to create a API Call to https://jsonplaceholder.typicode.com/posts/. I want to practice making the call, receive a JSON response and then..do stuff.

How can I finish this off to get a response so I can iterate through the response array.

using (HttpClient client = new HttpClient())
 {

                client.BaseAddress = new Uri(URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,"");
                request.Content = new StringContent(URL, Encoding.UTF8,"application/json");

Wiring this in VS Code so will need to install packages if needed.

Thank you!

  • Please read this question and ALL answer/comments...........to set up your code (well). https://stackoverflow.com/questions/52622586/can-i-use-httpclientfactory-in-a-net-core-app-which-is-not-asp-net-core – granadaCoder Jun 23 '20 at 20:52

1 Answers1

0

You are almost there. Try (if you want a simple synchronous send):

HttpClient client = new HttpClient();
string responseString;
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri("<insert your URL>"))) {
    HttpResponseMessage response = client.SendAsync(request).Result;
    
    // Get the response content as a string
    responseString = response.Content.ReadAsStringAsync().Result;
}

Note that it's good practice to initialize one instance of HttpClient and reuse it to send multiple requests (rather than initialize one every time you need to send something).

Any headers, URLs and such specific to a message should be set in the HttpRequestMessage class (which should be disposed of with the "using ..." term.

penguins
  • 76
  • 8