我创建了GetCourses()
方法,我使用HttpWebRequest
从显示的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)
{
}
}
答案 0 :(得分: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();
答案 1 :(得分:1)
当我运行它时,这很有用。您需要在关闭之前阅读流。作为旁注,许多人更喜欢使用using
关键字自动关闭其Streams。
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)
{
}