2010-03-22 45 views
2

我創建了一個具有函數mainpost的應用程序。它被創建爲在https網站上發佈數據。在這裏我想處理這個功能中的cookies。我該怎麼做這個任務?在webrequest和響應中處理cookie的問題

public string Mainpost(string website, string content) 
{ 
    // this is what we are sending 
    string post_data = content; 

    // this is where we will send it 
    string uri = website; 

    // create a request 
    HttpWebRequest request = (HttpWebRequest) 
    WebRequest.Create(uri); request.KeepAlive = false; 
    request.ProtocolVersion = HttpVersion.Version10; 
    request.Method = "POST"; 

    // turn our request string into a byte stream 
    byte[] postBytes = Encoding.ASCII.GetBytes(post_data); 

    // this is important - make sure you specify type this way 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.ContentLength = postBytes.Length; 
    Stream requestStream = request.GetRequestStream(); 

    // now send it 
    requestStream.Write(postBytes, 0, postBytes.Length); 
    requestStream.Close(); 

    // grab te response and print it out to the console along with the status 
    // code 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    string str = (new StreamReader(response.GetResponseStream()).ReadToEnd()); 
    Console.WriteLine(response.StatusCode); 

    return str; 
} 

回答

3

你需要做一個CookieContainer對象和每個HttpWebRequestCookieContainer屬性設置爲CookieContainer實例。

0

您需要在請求之間設置CookieContainer Property

如果您維護相同的cookie容器,cookies將會在將來的請求中被重新發送。