您需要通过 fiddler 观察 POST 请求并查看其结构。例如 :
{"userName":"you","password":"pwd"}
通常,网站会通过在您的请求中接收他们的 cookie 来识别您已登录。
默认情况下, HttpClient将从特定域接收到的 cookie 与每个顺序请求一起发送到该域(直到您处置该 HttpClient 实例)
1) 创建一个 cookie 容器并将其分配给您的 HttpClient 实例。
2) 使用 HttpClient 发出登录 POST 请求。
3) 使用 HttpClient 进行数据 GET 请求。
4) 从响应中读取 html 字符串。
5) 使用 HtmlAgilityPack HtmlDocument 从 html 字符串加载文档,而不是从网络加载文档(如大多数示例所示)。
string baseUrl = "https://www.yourwebsite.com";
string loginUrl = "/Account/LogOn";
string sessionUrl = "/Data";
var uri = new Uri(baseUrl);
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
client.BaseAddress = uri;
var request = new { userName = "you", password = "pwd" };
var resLogin = client.PostAsJsonAsync(loginUrl,request).Result;
if (resLogin.StatusCode != HttpStatusCode.OK)
Console.WriteLine("Could not login -> StatusCode = " + resLogin.StatusCode);
// see what cookies are returned
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);
var resData = client.GetAsync(dataUrl).Result;
if(resSession.StatusCode != HttpStatusCode.OK)
Console.WriteLine("Could not get data html -> StatusCode = " + resSession.StatusCode);
var html = resSession.Content.ReadAsStringAsync().Result;
var doc = new HtmlDocument();
doc.LoadHtml(html);
}