当未经身份验证的客户端 ( 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 证书。