2

我创建了用于从显示的 Url 请求数据的GetCourses()方法。HttpWebRequest如果我将 url 复制粘贴到浏览器中,浏览器将显示 xml 数据。我还使用提琴手做一些请求。在提琴手上,它说数据已编码,我必须对其进行解码。所以,我点击了解码,我可以看到 XML。但是,使用下面的代码,我得到了 Content-Length=-1。

public static void GetCourses()
    {
        try
        {
            HttpWebRequest requestForItCourse =
               (HttpWebRequest)WebRequest.Create("http://www.mnsu.edu/schedule/direct.php?action=courses&term=20135&subject=it");
            requestForItCourse.AutomaticDecompression = DecompressionMethods.GZip|DecompressionMethods.Deflate;
            HttpWebResponse responseFromMnsuDirectPhp =
                (HttpWebResponse)requestForItCourse.GetResponse();

            Stream dataStream = responseFromMnsuDirectPhp.GetResponseStream();
            responseFromMnsuDirectPhp.Close();
//Parse and insert courses into the database
        }
        catch (Exception ex)
        {

        }
    }
4

2 回答 2

2

您需要在关闭响应之前阅读响应流。

试试这个:

HttpWebRequest requestForItCourse = (HttpWebRequest)WebRequest.Create("http://www.mnsu.edu/schedule/direct.php?action=courses&term=20135&subject=it");
requestForItCourse.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
HttpWebResponse responseFromMnsuDirectPhp = (HttpWebResponse)requestForItCourse.GetResponse();

StreamReader dataStream = new StreamReader(responseFromMnsuDirectPhp.GetResponseStream());
string data = dataStream.ReadToEnd();

responseFromMnsuDirectPhp.Close();
dataStream.Close();
于 2013-03-07T20:18:27.093 回答
1

这在我运行时有效。您需要在关闭流之前阅读它。作为旁注,许多人更喜欢使用using关键字自动关闭他们的流。

try
{
    HttpWebRequest requestForItCourse = (HttpWebRequest)WebRequest.Create("http://www.mnsu.edu/schedule/direct.php?action=courses&term=20135&subject=it");
    requestForItCourse.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    HttpWebResponse responseFromMnsuDirectPhp =
                (HttpWebResponse)requestForItCourse.GetResponse();

    string raw_xml;
    using(var sr = new StreamReader(responseFromMnsuDirectPhp.GetResponseStream()))
    {
        raw_xml = sr.ReadToEnd();
    }

    //Parse and insert courses into the database
}
catch (Exception ex)
{

}
于 2013-03-07T20:19:50.363 回答