2

要访问该页面,我需要密码。我有密码,我可以访问该页面。

DownloadString(URL) 函数正在下载登录页面的内容,而不是我想要的实际页面。为什么?

using (var client = new WebClient())
            {
                var credentials = new NetworkCredential { UserName = "username", Password = "password" };
                client.Credentials = credentials;

                string pageContents = client.DownloadString(url);

                if (pageContents.Contains("cheetah"))
                {
                    MessageBox.Show("yes!");
                }
                else
                {
                    MessageBox.Show("No");
                }
            }

以上是获取登录页面的内容,而不是我真正想要的页面。我如何通过这个?

4

1 回答 1

3

当未经身份验证的客户端 ( WebClient.DownloadString) 请求页面时,通常会将其重定向到他们可以进行身份​​验证的登录表单。一旦凭据通过并确认,客户端通常会被带回他们最初请求的页面。

要通过这个,您需要模拟身份验证,这通常包括传递用户名和密码、接受 cookie 以及使用 cookie 进行进一步的请求。在最基本的层面上,这应该说明该方法:

using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace HttpsRequest
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var cookieContainer = new CookieContainer();
            var loginRequest = WebRequest.CreateHttp("https://your.url.net/login");
            loginRequest.CookieContainer = cookieContainer;
            var response = loginRequest.Post("Login=foo&Password=bar");
            Debug.Assert(response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent);

            var homeRequest = WebRequest.CreateHttp("https://your.url.net/home");
            homeRequest.CookieContainer = cookieContainer;
            Debug.Assert(response.StatusCode == HttpStatusCode.OK);
            homeRequest.GetResponse().Body();
        }

        internal static HttpWebResponse Post(this HttpWebRequest request, string data)
        {
            try
            {
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                var encoding = new ASCIIEncoding();
                var dataAsBytes = encoding.GetBytes(data);
                request.ContentLength = dataAsBytes.Length;
                var stream = request.GetRequestStream();
                stream.Write(dataAsBytes, 0, dataAsBytes.Length);
                stream.Close();
                return (HttpWebResponse)request.GetResponse();
            }
            catch (WebException we)
            {
                return (HttpWebResponse)we.Response;
            }
        }

        internal static string Body(this WebResponse response)
        {
            var stream = response.GetResponseStream();
            using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
            {
                return reader.ReadToEnd();
            }
        }
    }
}

为了使其工作,您可能希望查看使用 Fiddler、FireBug 或类似工具从浏览器发送到站点的实际请求,然后尝试尽可能多地模拟它。例如,该站点可能需要其他或不同的 post 字段、HTTP 标头或具有无效的 SSL 证书。

于 2012-11-08T00:23:33.023 回答