简体   繁体   中英

Saving login Cookie and use it for other request

I'm new to c#. I'm trying to login to a website, using ac# post request.

Does this code save the cookie actually to the CookieContainer and would it let me use this cookie in other requests also? How would I for example post a get request now with the cookie I saved from the login?

My main code:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string userName = textBox1.Text;
        string passWord = textBox2.Text;
        string postData = "username=" + userName + "&password=" + passWord;
        string requestUrl = "http://registration.zwinky.com/registration/loginAjax.jhtml";

        post botLogin = new post();
        botLogin.postToServer (postData ,requestUrl);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error :" + ex.Message);
    }
}

My post class:

public class post
{
    public void postToServer(string postData, string requestUrl)
    {
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
        myHttpWebRequest.Method = "POST";

        byte[] data = Encoding.ASCII.GetBytes(postData);

        myHttpWebRequest.CookieContainer = new CookieContainer();

        myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
        myHttpWebRequest.ContentLength = data.Length;

        Stream requestStream = myHttpWebRequest.GetRequestStream();
        requestStream.Write(data, 0, data.Length);
        requestStream.Close();

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

        Stream responseStream = myHttpWebResponse.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);

        string pageContent = myStreamReader.ReadToEnd();

        myStreamReader.Close();
        responseStream.Close();

        myHttpWebResponse.Close();
        MessageBox.Show(pageContent);
    }
}

You need to share the CookieContainer between the requests and the responses. I have similar code currently working:

public YourClass
{
    private CookieContainer Cookies;

    public YourClass()
    {
        this.Cookies= new CookieContainer(); 
    }

    public void SendAndReceive()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(...);
        ....
        request.UserAgent = agent;
        request.Method = "GET";
        request.ContentType = "text/html";
        request.CookieContainer = this.Cookies;
        ....

        this.Cookies = (HttpWebResponse)request.GetResponse().Cookies;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM