2015-06-22 72 views
1

我是新来的c#。我正尝试使用c#post请求登录到网站。保存登录Cookie并将其用于其他请求

此代码是否实际上将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); 
    } 
} 
+0

谢谢你。我检查出来。 –

回答

1

您需要的请求和响应之间共享的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; 
    } 
} 
+0

所以我必须先将cookie添加到cookie容器中: myHttpWebRequest.CookieContainer = new CookieContainer(); myHttpWebRequest.CookieContainer.Add(myHttpWebResponse.Cookies); 然后在进一步的请求中,我会简单地加载这个cookie? request.CookieContainer = new CookieContainer(); –

+0

是的,我认为是。根据我的经验,每个响应都会返回Cookie,因此我只是将其复制回每个请求。 –

+0

所以你把cookie添加到CookieContainer中,但是我现在怎么把它加载到其他请求中呢? –

相关问题