【问题标题】:c# httpwebrequest credential problemc# httpwebrequest 凭证问题
【发布时间】:2011-03-08 12:45:22
【问题描述】:

我正在尝试使用 httpwebrequest 对象登录www.diary.com。但是,它总是无法登录,并不断给我返回登录页面。谁能告诉我什么是错的?

我的代码如下:

// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
    WebRequest.Create(@"http://diary.com/events/agenda");

request.ContentType = "text/html";

request.Credentials = new NetworkCredential(@"user@hotmail.com", "password");

request.AllowAutoRedirect = true;
request.Referer = @"http://diary.com/";

// execute the request
HttpWebResponse response = (HttpWebResponse)
    request.GetResponse();

// we will read data via the response stream
Stream resStream = response.GetResponseStream();

// set the WebBrowser object documentStream to the response stream
myWB.DocumentStream = resStream;

// simply tell me the title of the webpage
MessageBox.Show(myWB.Document.Title);

【问题讨论】:

    标签: c# httpwebrequest screen-scraping credentials


    【解决方案1】:

    这里有两个问题:

    1. 您在协议级别提供凭据,这不是大多数网站(包括这个)的工作方式。该协议是完全匿名的,并且该站点使用表单身份验证来让您登录。您的代码需要实际创建一个模拟提交登录表单的 POST 请求。从服务器返回的响应将包含一个包含您的身份验证令牌的 cookie,它会导致...

    2. 您需要跨请求保留 cookie。提交登录请求并获取 cookie 后,您需要保留它并将其发送到每个后续请求的请求标头中。最简单的方法是使用WebClient 跨越多个请求,使用CookieContainer 为您跟踪cookie。

    如果您不确定如何模拟浏览器和网站之间的流量,Fiddler 是一个很好的工具。它捕获原始请求/响应供您观察。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      相关资源
      最近更新 更多