您需要通過fiddler觀察POST請求並查看它的結構。 例如:
{"userName":"you","password":"pwd"}
通常情況下,網站會認識到你是在收到您的要求自己的cookie登錄。
HttpClient默認情況下將來自與每個連續的請求到該域的特定域接收餅乾(除非你是處置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);
}
感謝您的幫助。 我看了一下,但由於我正在登錄的網站的奇怪源代碼,我肯定需要使用HTMLAgilityPack。 我已經做了一些事情,但之後我有點卡住了:我通過webbrowser1控制登錄,然後檢索該會話的cookie。我可以使用HTMLAgilityPack應用該cookie並使用該cookie打開頁面嗎? – touyets
@ user1842134 - 不,HAP不會處理cookie。 – Oded
好的非常感謝你 – touyets