2013-03-07 50 views
2

我創建了GetCourses()方法,其中我使用HttpWebRequest從所示的Url請求數據。如果我在瀏覽器中複製粘貼網址,瀏覽器將顯示xml數據。我也用小提琴手做了一些要求。在提琴手它說,數據編碼,我必須解碼它。所以,我點擊解碼,我可以看到XML。但是,使用下面的代碼我回到Content-Length = -1。httpwebrequest getresponse()不返回任何內容,而提琴手顯示內容

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

您確定關閉響應,然後閱讀流?這沒有任何意義。當你關閉你的響應時,你也會使底層數據不可用。 – user1908061 2013-03-07 20:12:21

+0

確保您在關閉響應之前閱讀該流,如果是的話,請確保您發送了用戶代理和引用者標頭,某些網站會被編碼以檢測刮板 – bizzehdee 2013-03-07 20:14:08

+0

謝謝大家 – shresthaal 2013-03-07 20:25:57

回答

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) 
{ 

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