繁体   English   中英

带有用户名和密码的System.Net.WebClient

[英]System.Net.WebClient with username and password

我有一个WebClient对象,并且正在使用DownloadFileAsync方法来获取文件,尽管在我需要登录该站点之前,这似乎很困难。 我想登录https://ssl.rapidshare.com/ (似乎正在使用Forms身份验证)。 我发现以下可识别Cookie的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));

为什么会这样呢?

您是否可以在System.Net命名空间中使用HttpWebRequest类 与用于发出HTTP请求的轻量级WebClient相比,这是一个灵活得多的类,它包含诸如HttpWebRequest.CookieContainer Property之类的东西。

如果网站使用基于cookie的身份验证而不是HTTP基本身份验证,则需要将cookie放入CookieContainer中,而不是设置凭据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM