Use the following method to Get cookie...
private static string GetCookie()
{
string uri = string.Empty;
string cookie = string.Empty;
HttpWebResponse response = POST(uri);
if (response == null)
{
this.LoginStatus = "Not connected";
return "";
}
WebHeaderCollection headers = response.Headers;
if ((response.StatusCode == HttpStatusCode.Found) ||
(response.StatusCode == HttpStatusCode.Redirect) ||
(response.StatusCode == HttpStatusCode.Moved) ||
(response.StatusCode == HttpStatusCode.MovedPermanently))
{
if (headers["Set-Cookie"] != null)
{
string cookies = headers["Set-Cookie"];
String[] fields = Regex.Split(cookies, ";\\s*");
cookie = fields[0];
}
}
return cookie;
}
public static HttpWebResponse POST(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
catch
{
return (HttpWebResponse)null;
}
}
Now you can use the cookie returned and use it another POST or GET, post sample below:
public static HttpWebResponse POST(string postData, string url, string referer, string cookie)
{
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
request.Accept = "*/*";
request.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(cookie))
request.Headers.Add(HttpRequestHeader.Cookie, cookie);
if (!string.IsNullOrEmpty(referer))
request.Referer = referer;
request.ContentLength = byteArray.Length;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
return (HttpWebResponse)request.GetResponse();
}
catch
{
return (HttpWebResponse)null;
}
}
catch
{
return (HttpWebResponse)null;
}
}