C#-HttpClient模拟登录Cookie问题

 模拟登录机锋论坛时 想要保持会话,起初设想WebReques的方法想通过获取响应的Cookie来实现。一番测试没成功。后经查阅资料HttpClient自动保存Cookie,只要是同一个HttpClient请求就可以实现保持登录状态。以下测试代码

public static void Login()
            {
                HttpClient httpClient = new HttpClient();//创建请求
                //httpClient.MaxResponseContentBufferSize = 256000;
                httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134");
                String url = "http://my.gfan.com/doLogin";
                List> paramList = new List>();//构建表单数据
                paramList.Add(new KeyValuePair("loginName", "8"));
                paramList.Add(new KeyValuePair("password", "do"));
                paramList.Add(new KeyValuePair("autoLogin", "0"));

                paramList.Add(new KeyValuePair("referer", "http://my.gfan.com/login"));
    

               HttpResponseMessage response = httpClient.PostAsync(new Uri(url), new FormUrlEncodedContent(paramList)).Result;
               var cookie = response.Headers.GetValues("Set-Cookie");
               String  result = response.Content.ReadAsStringAsync().Result;
               Console.WriteLine(result);
                //Get请求访问账号信息页面
                string url_2 = "http://my.gfan.com/account";
                HttpResponseMessage responseMessage = httpClient.GetAsync(new Uri(url_2)).Result;//使用之前的HttpClient
                String result_2 =responseMessage.Content.ReadAsStringAsync().Result;
                Console.WriteLine(result_2);
            }

 

你可能感兴趣的:(C#)