【问题标题】:System.Net.WebClient with username and password带有用户名和密码的 System.Net.WebClient
【发布时间】:2011-06-16 00:31:17
【问题描述】:

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

为什么会这样?

【问题讨论】:

    标签: c# cookies login webclient


    【解决方案1】:

    您可以在System.Net 命名空间中使用HttpWebRequest Class 吗?这是一个比用于发出 HTTP 请求的轻量级 WebClient 灵活得多的类,并且包含 HttpWebRequest.CookieContainer Property 之类的内容。

    【讨论】:

    • 嗨,丹,是的,我想我可以,但据我所知,上面的代码可以识别 WebClient cookie,所以我不确定为什么不能使用它?
    • @R4D4 因为它不与您的代码合作,也许吧? :)
    • 哈哈哈,我想这可能是原因之一! :) 尽管似乎有一些与此相关的答案都说 WebClient 重载是可能的(例如stackoverflow.com/questions/1777221/…)。如果我切换到 HttpWebRequest,我想我仍然不知道如何处理 cookie...谢谢。
    • 是的,我认为 HttpWebRequest 会做...... :)
    【解决方案2】:

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

    【讨论】:

    • 非常感谢您的评论;虽然我不能说我太确定如何使用 WebClient 获取 cookie?
    猜你喜欢
    • 1970-01-01
    • 2015-05-18
    • 2011-02-05
    • 2019-07-30
    • 2013-08-26
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多