3

im building an app that after the the user logs in to my web site the app goes to a link to get his user name so i will recognize him on the app.

Now if i as a user login from a browser and then paste the like on that browser i will get a page with my username but if i do a web request from code i get an empty page.

My question is how to open the url as a browser or how can i get the value of the cookie on a certin browser

i have tryied

string s= GetHtmlPage("http://www.somedomain.com/account/show_cookies.php","Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)");

 static string GetHtmlPage(string strURL,string browser)
        {
            String strResult;
            System.Net.WebResponse objResponse;

            System.Net.WebRequest objRequest = System.Net.HttpWebRequest.Create(strURL);
            ((System.Net.HttpWebRequest)objRequest).UserAgent =browser;
            objResponse = objRequest.GetResponse();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
            {
                strResult = sr.ReadToEnd();
                sr.Close();
            }
            return strResult;
        }

But that also return a blank page.

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
user1839169
  • 207
  • 2
  • 4
  • 16

1 Answers1

1

You need to use HttpClient and CookieContainer

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync("http://google.com").Result;

Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
     Console.WriteLine(cookie.Name + ": " + cookie.Value);

Console.ReadLine();
AndreyMaybe
  • 309
  • 1
  • 2
  • 8
  • i tryied it but it dosent return anything do you know of a way to accsess the page as a browser? – user1839169 Jun 15 '13 at 15:11
  • very strange, I have everything working correctly. try to go to Google several times and then run the program. insert your address instead of Google address – AndreyMaybe Jun 16 '13 at 09:03
  • http://msdn.microsoft.com/ru-ru/library/system.net.httpwebrequest.cookiecontainer.aspx – AndreyMaybe Jun 16 '13 at 09:51
  • http://stackoverflow.com/questions/1777221/using-cookiecontainer-with-webclient-class – AndreyMaybe Jun 16 '13 at 09:51
  • Default cookies will come down with every request but things like login or session cookies aren't going to travel from browser to browser. This is why a special cookie won't be available when you open it from your application after setting it via a specific browser. I'd like to know of a way to read the cookies too, maybe from the file system? – ParanoidCoder Aug 07 '18 at 23:49