HttpClient GetStreamAsync and HTTP status codes?

I want to use streams as recommended by json.net performance documentation , however I cannot find a way to hold http status codes without the typical HttpResponse wait .

Perhaps there is a way to get the status code without reading the data? So still using streams?

+5
source share
2 answers

I have not tested it, but this seems promising:

using(HttpClient client = new HttpClient()) { var response = await client.GetAsync("http://httpbin.org/get", HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync()) using (var streamReader = new StreamReader(stream)) using (var jsonReader = new JsonTextReader(streamReader)) { var serializer = new JsonSerializer(); //do some deserializing http://www.newtonsoft.com/json/help/html/Performance.htm } } 
+9
source

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(); //do some deserializing http://www.newtonsoft.com/json/help/html/Performance.htm } } else { //do your error logging and/or retry logic } } } 

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"); /* * execute */ 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(); //do some deserializing http://www.newtonsoft.com/json/help/html/Performance.htm } } } catch (WebException ex) { using (HttpWebResponse response = (HttpWebResponse)ex.Response) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { string respStr = sr.ReadToEnd(); int statusCode = (int)response.StatusCode; //do your status code logic here } } } 
+2
source

All Articles