1

一直在寻找解决方案,但我无法得到回答我问题的结果。

我正在寻找一种使用 HttpClient 浏览网站的方法(基本上是阅读 html)。我正在为 Windows 手机制作应用程序,因此某些选项可能会被禁用。

我想制作一个程序,该程序可以访问站点,登录,然后能够检索访问 html 源代码。

因此,当我登录时,会话 ID 会保存在 CookieContainer 中,因此我将能够访问需要登录的站点。我将如何使用 HttpClient :) 来做到这一点?

4

1 回答 1

2

HttpClient manages authentication cookies automatically for you. Just make sure you re-use the same HttpClient instance for multiple requests. Under the covers, HttpClient creates an instance of HttpClientHandler which has a CookieContainer.

Here is an example that logs into the NerdDinner site and retrieves a secured page.

        var httpClient = new HttpClient();

        // Create login payload
        var body = new Dictionary<string, string>() 
        {
            {"UserName",  "bob"},
            {"Password", "xyz"},
            {"RememberMe", "false"}
        };
        var content = new FormUrlEncodedContent(body);

        // POST to login form
        var response = await httpClient.PostAsync("http://www.nerddinner.com/Account/LogOn?returnUrl=%2F", content);

        // Make new request to secured resource
        var myresponse = await httpClient.GetAsync("http://www.nerddinner.com/Dinners/My");

        var stringContent = await myresponse.Content.ReadAsStringAsync();
于 2013-10-28T14:11:30.183 回答