I prefer to get rid of HttpResponseMessage through using , as it is one-time. I also prefer not to rely on exception handling to handle failed requests. Instead, I prefer to check the boolean value of IsSuccessStatusCode and act accordingly. For instance:
using(HttpClient client = new HttpClient()) { using(var response = await client.GetAsync("http://httpbin.org/get", HttpCompletionOption.ResponseHeadersRead)) { if(response.IsSuccessStatusCode) { using (var stream = await response.Content.ReadAsStreamAsync()) using (var streamReader = new StreamReader(stream)) using (var jsonReader = new JsonTextReader(streamReader)) { var serializer = new JsonSerializer();
EDIT: If you are doing work at speed , sending a HEAD request is simply not always possible. So here's a sample code using the good ol 't HttpWebRequest (note that in this case there is no better way to handle HTTP errors than WebException ):
var req = WebRequest.CreateHttp("http://httpbin.org/get"); try { using (var resp = await req.GetResponseAsync()) { using (var s = resp.GetResponseStream()) using (var sr = new StreamReader(s)) using (var j = new JsonTextReader(sr)) { var serializer = new JsonSerializer();
source share