0

I login with HTTPWebRequest and transfer the CookieContainer to the new class and want my WebClient to log in with this cookie and download a site as string. But I only get the source code of the login page, so it seems like the webclient won't login.

This is my current code:

        BasicAuthentication login = new BasicAuthentication();
        CookieContainer cookieJar = login.getCookie();

        WebClientEx client = new WebClientEx();
        client.Cookies = cookieJar;

And the WebClientEx Class

    class WebClientEx : WebClient
{
    private CookieContainer _cookies;
    private string _ref;
    public WebClientEx()
    {
        _cookies = new CookieContainer();
    }
    public CookieContainer Cookies
    {
        get { return _cookies; }
        set { _cookies = value; }
    }
    protected override WebRequest GetWebRequest(System.Uri address)
    {
        var webReq = base.GetWebRequest(address);
        if (webReq is HttpWebRequest)
        {
            var req = (HttpWebRequest)webReq;
            req.CookieContainer = _cookies;
            if (_ref != null)
            {
                req.Referer = _ref;
            }
        }
        _ref = address.ToString();
        return webReq;
    }
    protected override void Dispose(bool disposing)
    {
        _cookies = null;
        base.Dispose(disposing);
    }
}
Zasam
  • 63
  • 2
  • 17
  • What does `BasicAuthentication.getCookie()` do? The *server* has to check the credentials and return a cookie to you. You can't create a cookie from the credentials on the client side and send it with each request. Typically, you *post* the credentials to a login form and receive the cookie in the response. – Panagiotis Kanavos Mar 15 '17 at 15:06
  • Instead of WebClient, try HttpClient. You can configure it with a CookieContainer through its HttpClientHandler, [as shown here](http://stackoverflow.com/questions/12373738/how-do-i-set-a-cookie-on-httpclients-httprequestmessage). You don't have to override `GetWebRequest` anymore – Panagiotis Kanavos Mar 15 '17 at 15:10
  • Thanks for comments guys. I achived my aim. Should I post my answer or delete the post`? I'm new to stackoverflow. – Zasam Mar 15 '17 at 15:53
  • @N.iw just post your answer as an aswer & accept it – Lanorkin Mar 16 '17 at 06:19

1 Answers1

2

I just get an Answer to my question. Here's a example of my code:

        WebClient client = new WebClient();
        client.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
        string download = client.DownloadString("url");
        output.Text = download;

In the variable cookievalue I only enter the cookiename=cookievalue. I get the name and the value from Postman, a useful google chrome tool.

I just have to make sure that i can redirect to any login proteccted page with postman and when this is true, then I can use cookiename and cookievalue to login my webclient and see all pages and download sites with downloadString.

Zasam
  • 63
  • 2
  • 17