httpWebRequest保持session的方法



      httpWebRequest每次请求,服务端是不同的Session, 对于需要登录保持Session才能操作的页面,无法进行。这就要求程序每次请求在同一个Session中。

网上有许多保持Session的说明,都不够直接。这里特别说明一下。

      服务端每次识别客户端在同一个Session访问,是基于cookie中有SessionID值。每次访问服务端时, 服务端通过识别客户请求的cookie的SessionID值,来判断是否在同一个Session中。

     解决方法就是在登录成功后,获取请求的cookie, 在下次请求时,将cookie赋值给HttpWebRequest.CookieContainer,就可以成功访问了。

          

            //创建cookie 

            CookieContainer cookies = new CookieContainer();
            HttpWebRequest webRequest;

            //登录LOGIN_URL

            webRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";


           // 赋值给webRequest.CookieContainer 


            webRequest.CookieContainer = cookies;

            StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
            string postData = "username="+tUsername.Text.Trim()+"&password="+tPassword.Text.Trim();
            requestWriter.Write(postData);
            requestWriter.Close();

            StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();
            webRequest.GetResponse().Close();

            //获取登录成功后的cookie

            CookieCollection cookieheader = webRequest.CookieContainer.GetCookies(new Uri(LOGIN_URL));
            cookies.Add(cookieheader)
;

            //访问其它页面PAGE_URL

            webRequest = (HttpWebRequest)WebRequest.Create(PAGE_URL);

           // 核心关键:赋值给webRequest.CookieContainer,这时就可以成功访问
            webRequest.CookieContainer = cookies;
            webRequest.ContentType = "application/x-www-form-urlencoded";
            StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream(), Encoding.GetEncoding("utf-8"));
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();

请参看:http://download.csdn.net/detail/c6088/7888301

你可能感兴趣的:(httpWebRequest保持session的方法)