2010-05-09 30 views
5

我正在嘗試登錄TV Rage網站並獲取My Shows頁面的源代碼。我正在成功登錄(我檢查了我發佈的請求中的回覆),但是當我嘗試在「我的展示」頁面上執行獲取請求時,我被重定向到登錄頁面。登錄網站,然後通過cookies獲得另一頁的源代碼

這是我使用的登錄代碼:

private string LoginToTvRage() 
    { 
     string loginUrl = "http://www.tvrage.com/login.php"; 
     string formParams = string.Format("login_name={0}&login_pass={1}", "xxx", "xxxx"); 
     string cookieHeader; 
     WebRequest req = WebRequest.Create(loginUrl); 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.Method = "POST"; 
     byte[] bytes = Encoding.ASCII.GetBytes(formParams); 
     req.ContentLength = bytes.Length; 
     using (Stream os = req.GetRequestStream()) 
     { 
      os.Write(bytes, 0, bytes.Length); 
     } 
     WebResponse resp = req.GetResponse(); 
     cookieHeader = resp.Headers["Set-cookie"]; 
     String responseStream; 
     using (StreamReader sr = new StreamReader(resp.GetResponseStream())) 
     { 
      responseStream = sr.ReadToEnd(); 
     } 
     return cookieHeader; 
    } 

我再通過cookieHeader這個方法,它應該得到我的源顯示頁面:

private string GetSourceForMyShowsPage(string cookieHeader) 
    { 
     string pageSource; 
     string getUrl = "http://www.tvrage.com/mytvrage.php?page=myshows"; 
     WebRequest getRequest = WebRequest.Create(getUrl); 
     getRequest.Headers.Add("Cookie", cookieHeader); 
     WebResponse getResponse = getRequest.GetResponse(); 
     using (StreamReader sr = new StreamReader(getResponse.GetResponseStream())) 
     { 
      pageSource = sr.ReadToEnd(); 
     } 
     return pageSource; 
    } 

我有一直在使用this previous question作爲指南,但我爲什麼我的代碼無法正常工作而茫然。

回答

17

這是你的代碼的簡化和工作版本使用WebClient

class Program 
{ 
    static void Main() 
    { 
     var shows = GetSourceForMyShowsPage(); 
     Console.WriteLine(shows); 
    } 

    static string GetSourceForMyShowsPage() 
    { 
     using (var client = new WebClientEx()) 
     { 
      var values = new NameValueCollection 
      { 
       { "login_name", "xxx" }, 
       { "login_pass", "xxxx" }, 
      }; 
      // Authenticate 
      client.UploadValues("http://www.tvrage.com/login.php", values); 
      // Download desired page 
      return client.DownloadString("http://www.tvrage.com/mytvrage.php?page=myshows"); 
     } 
    } 
} 

/// <summary> 
/// A custom WebClient featuring a cookie container 
/// </summary> 

public class WebClientEx : WebClient 
{ 
    public CookieContainer CookieContainer { get; private set; } 

    public WebClientEx() 
    { 
     CookieContainer = new CookieContainer(); 
    } 

    protected override WebRequest GetWebRequest(Uri address) 
    { 
     var request = base.GetWebRequest(address); 
     if (request is HttpWebRequest) 
     { 
      (request as HttpWebRequest).CookieContainer = CookieContainer; 
     } 
     return request; 
    } 
} 
+0

這是完美的!非常感謝你! – Stu 2010-05-09 19:35:42

相關問題