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

本文关键字:其他 请求 用于 登录 Cookie 保存 | 更新日期: 2023-09-27 17:57:26

我是c#的新手。我正在尝试登录一个网站,使用c#帖子请求。

这段代码是否将cookie保存到CookieContainer中?它是否也允许我在其他请求中使用此cookie?例如,我现在如何用登录时保存的cookie发布get请求?

我的主要代码:

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

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

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

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