保存登录Cookie并将其用于其他请求

时间:2015-06-22 10:37:51

标签: c# post cookies

我是c#的新手。我正在尝试使用c#post请求登录网站。

此代码是否将cookie实际保存到CookieContainer中,是否允许我在其他请求中使用此cookie?例如,我如何使用我从登录中保存的cookie发布获取请求?

我的主要代码:

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);
    }
}

我的帖子课:

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);
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在请求和响应之间共享CookieContainer。我目前有类似的代码:

nextBlock = [CCBReader load: @"NextBlock" owner:self];