10

I am logging into a site using a WebBrowser, then i want use regex to get some data , but webRequest didnt use web Browse cookie ,

my webBrowser is in public , is there any way to using WebBrowser cookie in webRequest ?

Question Guy
  • 237
  • 1
  • 2
  • 16
madman
  • 319
  • 2
  • 6
  • 19
  • really simple i want use it for getting news :) but site protected by login page , so this way easiest to login :) – madman Mar 16 '09 at 14:33

3 Answers3

12
    public CookieContainer GetCookieContainer()
    {
        CookieContainer container = new CookieContainer();

        foreach (string cookie in webBrowser1.Document.Cookie.Split(';'))
        {
            string name = cookie.Split('=')[0];
            string value = cookie.Substring(name.Length + 1);
            string path = "/";
            string domain = ".google.com"; //change to your domain name
            container.Add(new Cookie(name.Trim(), value.Trim(), path, domain));
        }

        return container;
    }

This will work on most sites, however sites that use subdomains might be a problem.

Jakub
  • 213
  • 4
  • 11
7

You can use a CookieContainer for a Webrequest.

 web_cookies = new CookieContainer();
 // Create a 'WebRequest' object with the specified url.                 
 HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url);

 myWebRequest.CookieContainer = web_cookies;

Hope this helps.

Ok, you want to do a log in. Thats is different story. You can use NetworkCredential for that.

public string get_secure_webpage(string url, string username, string password)
    {
        WebRequest myWebRequest = WebRequest.Create(url);
        NetworkCredential networkCredential = new NetworkCredential(username, password);
        myWebRequest.Credentials = networkCredential;

...

TalkingCode
  • 13,407
  • 27
  • 102
  • 147
  • 1
    I am not exactly sure what you want to do. Maybe this page will help: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx – TalkingCode Mar 16 '09 at 15:49
  • 2
    Actually, most websites use cookies for auth rather than HTTP auth, so using a networkCredential won't help. Attaching the cookie container will work so long as it gets the IE cookies; if not, PInvoke to InternetGetCookie() – EricLaw Jan 08 '10 at 21:15
  • this is tottally outside the question. useless – Leandro Bardelli Aug 09 '22 at 18:07
0

is this silverlight? if so, since silverlight 3 if you use the browser network stack than you should get cookies for free. By default you get the browser stack when you create n HttpWebrequest using the WebRequest.Create() method. note if you use CreateHTTP method, you get a client stack, which does not include browser cookies by default (you have to do trickery to get them, as described previously)

see http://msdn.microsoft.com/en-us/library/dd920295(VS.95).aspx about the network stacks in silverlight since version 3

Chris DaMour
  • 3,650
  • 28
  • 37