I have successful connected to the login page, however, i\'m not sure how to login and grab the file thats behind the login. Below is the code i\'m using to make the connec
Fist thing, you need to initiate the cookie container before the first request:
CookieContainer cookies = new CookieContainer();
then you need to pass it on each request(now you're just instantiating it again, thus losing all the cookies):
request.CookieContainer = cookies;
the response you're getting will fill the cookie container with the necessary cookies.
Furthermore, as I see you are already doing, you need to perform a series of Request/Response on the website and track the cookies. Use a tool like Fiddler to see what exactly how you need to formulate your POST strings to correctly login to the website.
Your code has the following problems that I can see:
Try the following code:
Uri url = new Uri("http://app/templat");
HttpWebRequest request = null;
// Uncomment the line below only if you need to accept an invalid certificate, i.e. a self-signed cert for testing.
// ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
CookieContainer cookieJar = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieJar;
request.Method = "GET";
HttpStatusCode responseStatus;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
responseStatus = response.StatusCode;
url = request.Address;
}
if (responseStatus == HttpStatusCode.OK)
{
UriBuilder urlBuilder = new UriBuilder(url);
urlBuilder.Path = urlBuilder.Path.Remove(urlBuilder.Path.LastIndexOf('/')) + "/j_security_check";
request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
request.Referer = url.ToString();
request.CookieContainer = cookieJar;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(requestStream, Encoding.ASCII))
{
string postData = "j_username=user&j_password=user&submit=Send";
requestWriter.Write(postData);
}
string responseContent = null;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
responseContent = responseReader.ReadToEnd();
}
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Client was unable to connect!");
}