HttpClient GetStreamAsync和HTTP状态代码?

时间:2015-05-11 08:53:58

标签: c# stream json.net httpclient

我希望按照json.net performance tips documentation的建议使用流,但是我无法找到如何在没有typical awaiting the HttpResponse的情况下获取http状态代码。

是否有一种方法可以在不读取数据的情况下首先获取状态代码?所以仍然利用流?

1 个答案:

答案 0 :(得分:3)

我更喜欢通过using处理HttpResponseMessage,因为它是一次性的。我也更喜欢不依赖异常处理来处理失败的请求。相反,我更喜欢检查IsSuccessStatusCode布尔值并相应地继续。例如:

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
        }
    }       
}
  

编辑:如果你正在使用速率限制 api工作,发送HEAD请求有时是不可行的。因此,这是一个使用好的'时尚HttpWebRequest的代码示例(请注意,在这种情况下,没有比WebException更好的方法来处理http错误):

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
        }
    }
}