Httpwebrequest getresponse()不返回任何内容,而fiddler显示内容

本文关键字:显示 fiddler 任何内 getresponse 返回 Httpwebrequest | 更新日期: 2023-09-27 18:02:44

我创建了GetCourses()方法,其中我使用HttpWebRequest从所示的Url请求数据。如果我在浏览器中复制粘贴url,浏览器将显示xml数据。我还用fiddler做了一些请求。在小提琴上它说数据是编码的,我必须解码它。所以,我点击解码,我可以看到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)
        {
        }
    }

Httpwebrequest getresponse()不返回任何内容,而fiddler显示内容

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

试试这个:

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();

当我运行它时,它工作了。您需要在关闭流之前读取它。作为旁注,许多人更喜欢使用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)
{
}