WebRequest持久化 保存登录状态
这样的一个需求:
网站的接口需要验证session或者cookies是否登录过如果用WebRequest请求的话没有session或者cookies肯定是请求不成功的!
要想保存服务器登录之后的session或者cookies
原理很简单:
模拟提交一次登录请求然后保存session或者cookies下一次请求加入这个session,服务器验证到了请求中的session自然就可以了!
#region WebRequest提交 /// <summary> /// WebRequest提交 /// </summary> /// <param name="url"></param> /// <param name="parameter"></param> /// <param name="method"></param> /// <param name="requestcookie"></param> /// <param name="getcookie"></param> /// <param name="isgetcookie"></param> /// <returns></returns> public string SumitWebRequest(string url, string parameter, string method, CookieCollection reqCookie, ref CookieCollection resCookie) { string getOrderUrl = url; HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(getOrderUrl);//新建一个HttpWebRequest myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; myHttpWebRequest.CookieContainer = new CookieContainer(); myHttpWebRequest.Method = method; myHttpWebRequest.KeepAlive = false; if (reqCookie != null) { myHttpWebRequest.CookieContainer.Add(reqCookie); } if (!String.IsNullOrEmpty(parameter)) { Stream myRequestStream = myHttpWebRequest.GetRequestStream();//获取Request流 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.UTF8); myStreamWriter.Write(parameter); //把参数写入HttpWebRequest的Request流 myStreamWriter.Close(); myRequestStream.Close(); } HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); //提交获得响应 resCookie = myHttpWebRequest.CookieContainer.GetCookies(new Uri(url)); Stream myResponseStream = myHttpWebResponse.GetResponseStream();//获取Response流 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8); string result = myStreamReader.ReadToEnd();//把数据从HttpWebResponse的Response流中读出 myStreamReader.Close(); myResponseStream.Close(); return result; } #endregion