2011-06-15 126 views
1

我有一個WebClient對象,我正在使用DownloadFileAsync方法來獲取文件,雖然在我之前我需要登錄到網站,這似乎是一個困難。我想登錄到https://ssl.rapidshare.com/(似乎使用表單身份驗證)。我發現下面的Web客戶端代碼,餅乾意識到:帶有用戶名和密碼的System.Net.WebClient

public class CookieAwareWebClient:WebClient { 
    private CookieContainer m_container=new CookieContainer(); 
    protected override WebRequest GetWebRequest(Uri address) { 
     WebRequest request=base.GetWebRequest(address); 
     if(request is HttpWebRequest) { 
      (request as HttpWebRequest).CookieContainer=m_container; 
     } 
     return request; 
    } 
} 

但是,我怕我的代碼似乎沒有共同運行:

gWebClient=new CookieAwareWebClient(); 
if(gGroupEntry.GetStringProperty(CGroupEntry.EStringProperties.DownloadURL).Contains("rapidshare.com")) 
    gWebClient.Credentials=new System.Net.NetworkCredential(CSaverLoader.gUsername, CSaverLoader.gPassword, "https://ssl.rapidshare.com/"); 
gWebClient.DownloadFileCompleted+=new AsyncCompletedEventHandler(gWebClient_DownloadFileCompleted); 
gWebClient.DownloadProgressChanged+=new DownloadProgressChangedEventHandler(gWebClient_DownloadProgressChanged); 
gWebClient.DownloadFileAsync(new Uri(gGroupEntry.GetStringProperty(CGroupEntry.EStringProperties.DownloadURL)), gDownloadDirectory+"/"+gGroupEntry.GetStringProperty(CGroupEntry.EStringProperties.FileName)); 

爲什麼會這樣?

回答

1

您是否可以在System.Net名稱空間中使用HttpWebRequest Class?與輕量級WebClient相比,這是一個更靈活的類別,用於發出HTTP請求,幷包含諸如HttpWebRequest.CookieContainer Property之類的內容。

+0

嗨丹,是的,我想我可以儘管據我所知上面的代碼使WebClient cookie知道,所以我不知道爲什麼不能使用? – R4D4 2011-06-15 17:19:48

+0

@ R4D4因爲它不與你的代碼協作,也許? :) – 2011-06-15 17:53:29

+0

哈哈哈,嗯,我想這可能是一個原因! :)雖然似乎有一些與此相關的答案,都說可能重載WebClient(例如http://stackoverflow.com/questions/1777221/c-using-cookiecontainer-with-webclient-class)。如果我切換到HttpWebRequest,我想我仍然無法處理cookie的處理方式......謝謝。 – R4D4 2011-06-15 18:00:12

0

如果網站使用基於cookie的身份驗證而不是HTTP基本身份驗證,則需要將Cookie放入CookieContainer中,而不是設置憑據。

+0

非常感謝評論;雖然我不能說我太確定如何使用WebClient獲得cookie了嗎? – R4D4 2011-06-15 16:20:25