0

I'm using this code to login to website via POST request:

HttpWebRequest httpWReq =
    (HttpWebRequest)WebRequest.Create(@"http:\\domain.com\page.asp");

ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(data,0,data.Length);
}

HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Create HTTP post request and receive response using C# console application

It works fine, I get html string in response telling me that i'm loged in. But now I would like to for example get my profile data under different url. For example im login with "wwww.mywebsite.com/login" and second url is "www.mywebsite.com/myprofile". Am I able to get content from that second url? of course I can see this profile data only after login.

Community
  • 1
  • 1

1 Answers1

0

We can assume that the website uses cookies to transfer identity between the server and the web client. So if you want to make another request passing the authentication cookies, you should do something like this:

When login to the site at this point

 HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();

save all cookies that has been returned in the response this way:

 CookieCollection cookies = response.Cookies;

Then, when making another request, append the cookies:

 HttpWebRequest httpWReq =
       (HttpWebRequest)WebRequest.Create(@"http:\\www.mywebsite.com\myprofile");
 // other staff here 
 ...
 ...

 // then add saved cookies to the request
 httpWReq.CookieContainer.Add(cookies);

 // then continue executing the request
 ...
 ...
bugartist
  • 139
  • 3
  • Thank You for Your answer but response.Cookies is null :( I know there are some cookies because I checked it with Firefox plugin but there are none cookies in response object... – hamstermaner Mar 29 '13 at 16:24
  • Could you debug and check is there anything in 'response.Headers["Set-Cookie"]' – bugartist Mar 29 '13 at 16:34
  • Ok, Thanks to Your reply i could menage to do it. I've needed to add httpWReq.CookieContainer = new CookieContainer(); httpWReq.CookieContainer.Add(new Cookie("test", "xxxx", "/", "localhost")); to set cookies on before geting respone – hamstermaner Mar 29 '13 at 16:34
  • Yep... msdn says 'If the CookieContainer property of the associated HttpWebRequest is null, the Cookies property will also be null. Any cookie information sent by the server will be available in the Headers property, however.' – bugartist Mar 29 '13 at 16:37