简体   繁体   中英

Receiving incomplete data when using HttpWebResponse::GetResponseStream method

Is HttpWebResponse::GetResponseStream() guaranteed to get all data contained in an HTTP response? Or do I need to create some kind of loop and wait to make sure all data is being sent from the server to which I'm connected? The code below successfully grabs a response about 50% of the time.

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://JohnDoeServerSite.com");
    req.Method = "POST";
    req.ContentType = @"text/xml; charset=utf-8";
    req.Host = "http://JohnDoeServerSite.com";
    req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.1)";
    using (StreamWriter sw = new StreamWriter(req.GetRequestStream()))
    {
        sw.Write(xml);
    }
    string result;
    using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
    using (Stream st = res.GetResponseStream())
    {
        Thread.Sleep(10000);  //  Added to see if additional data would be sent (perhaps?)
        using (StreamReader sr = new StreamReader(st, Encoding.UTF8))
        {
            st.Flush();   
            result = sr.ReadToEnd();
        }
    }

After looking into this more, it turns out that the server was not sending all of the data in its entirety. It seems that Michael Yoon is right in saying that everything should be returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM