Can WebResponse.GetResponseStream() return a null?

前端 未结 2 1075
旧巷少年郎
旧巷少年郎 2021-01-17 11:29

i know its a noob question, but just wanted to know whether GetResponseStream() can return null in any case?

相关标签:
2条回答
  • 2021-01-17 11:39

    Well, it's sort of up to the concrete subclass - but I've never seen any subclass which does so, and it's not documented as a valid return value. I've never seen any code written to defensively check for this, and I wouldn't expect to. That's not to say such code doesn't exist, but I don't think it's necessary.

    If there's no content in the response (but the response was successful) I'd expect any good implementation to return an empty stream.

    0 讨论(0)
  • 2021-01-17 11:59

    No built-in type derived from WebResponse, in particular HttpWebResponse, can return null. This superstitious belief has misled many developers. Don't check for null. Such code is dead code.

    What would null even mean compared to returning an empty stream?! This does not make sense.

    Also, GetResponse() cannot return null. Again, what is that supposed to mean?! The HTTP protocol does not support the notion of a "null response". If that ever happens due to a library bug it's not possible to handle that situation anyway. Any such check does not help.

    It is possible to create classes derived from WebResponse that return an insane values such as null. No built-in class does that and it should be considered a bug to return null. Classes derived from WebResponse are very rare. I have never seen one.

    Here's a good code pattern to use:

    var request = WebRequest.Create("http://example.org/");
    
    using (var response = request.GetResponse())
    using (var responseStream = response.GetResponseStream())
    using (var responseReader = new StreamReader(responseStream))
    {
        var contents = responseReader.ReadToEnd();
    }
    

    It demonstrates how to succinctly and safely read the contents of an HTTP URL using HttpWebRequest.

    0 讨论(0)
提交回复
热议问题