2013-07-11 51 views
3

我想向HTTP服務器發出POST請求,但我需要在請求中「包含」一個cookie,我有cookie但我不知道如何混淆cookie容器C#從字符串中創建cookie併發送它

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
request.Method = "POST"; 
request.Accept = "text/javascript, text/html, application/xml, text/xml, */*"; 
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; 
request.Host = "url.com"; 
request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11"; 
request.Referer = "http://url.com"; 
request.Headers.Add("X-Requested-With", "XMLHttpRequest"); 
request.Headers.Add("X-Prototype-Version", "1.7"); 
request.Headers.Add("Accept-Encoding: gzip, deflate"); 

,這是一個示例的Cookie:

曲奇recentlyVisitedAppHubs = 233450%2​​C231430%2C48110%2C45760; Language =西班牙語; strInventoryLastContext = 440_2; __utma = 268881843.118202637.1372069740.1373472452.1373473085.10; __utmb = 268881843.21.10.1373473085; __utmz = 268881843.1373473085.10.4.utmcsr =谷歌| utmccn =(有機)| utmcmd =有機| utmctr =(未%20provided); rgTopicView_General_4312225 =%7B%22828934913396342649%22%3A%221373450285%22%2C%22846939615003500718%22%3A1373473557%7D; timezoneOffset = 7200,0;的sessionid = NDExNjE1NDE5; 登錄= 765611979917322708A9C768; steamRememberLogin = 76561197991732272; __utma = 268881843.118202637.1372069740.1373472452.1373473085.10; __utmb = 268881843.22.10.1373473085; __utmc = 268881843; __utmz = 268881843.1373473085.10.4.utmcsr =谷歌| utmccn =(有機)| utmcmd =有機| utmctr =(未%20provided)

但我不知道如何該cookie轉換成一個Cookie容器中,然後將其添加請求。 request.CookieContainer = cookie;

回答

3
//build uri and cookie 
Uri uri = new Uri("domain"); 
Cookie cookie = new Cookie("name", "value"); 

//build request 
HttpWebRequest request = WebRequest.Create("domain") as HttpWebRequest; 
request.CookieContainer = new CookieContainer(); 
request.CookieContainer.Add(uri, cookie); 

資源:

+0

但我只有字符串,我沒有CookieCollection對象。 –

+0

更新了構建Cookie對象的答案。 –

+0

仍然不回答這個問題。 –

1
String CookieStr = "recentlyVisitedAppHubs=233450%2C231430%2C48110%2C45760; 
Language=spanish; strInventoryLastContext=440_2"; 
CookieContainer cookiecontainer = new CookieContainer(); 
string[] cookies = CookieStr.Split(';'); 
foreach (string cookie in cookies) 
    cookiecontainer.SetCookies(new Uri("http://url.com"), cookie); 
request.CookieContainer = cookiecontainer; 
+1

歡迎來到Stack Overflow!請寫一個關於你的代碼的作用和不同的解釋,以便其他人可以理解! –

+0

從字符串創建cookie – artoor32