HttpClient
is intended to be instantiated once and reused throughout the life of an application.
- The following conditions can result in SocketException errors:
- Creating a new HttpClient instance per request.
- Server under heavy load.
- Creating a new HttpClient instance per request can exhaust the available sockets.
- The following code initializes the HttpClient instance:
client.BaseAddress = new Uri("<http://localhost:64195/>");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
GET
Request
- The
GetAsync
method sends the HTTP GET request.
- When the method completes, it returns an
HttpResponseMessage
that contains the HTTP response.
- If the status code in the response is a success code, the response body contains the JSON representation of a product.
- Call
ReadAsAsync
to deserialize the JSON payload to a Product
instance.
- The
ReadAsAsync
method is asynchronous because the response body can be arbitrarily large.
HttpClient
does not throw an exception when the HTTP response contains an error code.
- Instead, the IsSuccessStatusCode property is false if the status is an error code.
- If you prefer to treat HTTP error codes as exceptions, call
HttpResponseMessage.EnsureSuccessStatusCode
on the response object.
EnsureSuccessStatusCode
throws an exception if the status code falls outside the range 200–299.
- Note that
HttpClient
can throw exceptions for other reasons — for example, if the request times out.
Product product = null;
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
product = await response.Content.ReadAsAsync<Product>();
- When
ReadAsAsync
is called with no parameters, it uses a default set of media formatters to read the response body.
- The default formatters support JSON, XML, and Form-url-encoded data.
var formatters = new List<MediaTypeFormatter>
{
new MyCustomFormatter(),
new JsonMediaTypeFormatter(),
new XmlMediaTypeFormatter()
};
response.Content.ReadAsAsync<IEnumerable<Product>>(formatters);