Before, I had a hard time understanding on how to keep a certain session alive when using HttpWebRequest, and accessing a protected page where it requires login.
it turns out to be very easy, all you need to do is set the CookieContainer, notice that I declared the CookieContainer as static. This is so that different request can share the same cookie.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Net; namespace WebRequestSample { public abstract class RequestBase { protected static CookieContainer cookieContainer = null; protected HttpWebRequest CreateRequest(string uri) { if (RequestBase.cookieContainer == null) RequestBase.cookieContainer = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.CookieContainer = cookieContainer; return request; } } }
Now all you need to do is inherit RequestBase. and call CreateRequest
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Net; namespace WebRequestSample { public class SampleRequest : RequestBase { public void Login(string postToFormAddress, string username, string password) { HttpWebRequest request = this.CreateRequest(postToFormAddress); //note: you need to check the html form and make sure to post all input variables including the submit button value string loginData = string.Format("username={0}&password={1}&submit=login", username, password); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] loginDataBytes = encoding.GetBytes(loginData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = loginDataBytes.Length; Stream stream = request.GetRequestStream(); stream.Write(loginDataBytes, 0, loginDataBytes.Length); stream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string htmlBuffer = sr.ReadToEnd(); // todo: check the htmlBuffer if it contains data that requires login, if you find it then you have successfuly logged in! } } }