c#httpwebrequest凭证问题

Bec*_*coZ 1 c# screen-scraping credentials httpwebrequest

我正在尝试使用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);
Run Code Online (Sandbox Code Playgroud)

Rex*_*x M 5

你有两个问题:

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

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

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