2012-07-26 73 views
4

我正在嘗試使用.NET 4.5 HttpClient登錄到網站並收到一個cookie。在離開這個試驗之前我打破了它,並檢查了CookieContainer並且它沒有包含cookies。儘管如此,該響應會發回200狀態。C#Metro HttpClient未在PostAsync上接收cookie

private async void Login(string username, string password) 
{ 
    try 
    { 
     Uri address = new Uri(@"http://website.com/login.php"); 
     CookieContainer cookieJar = new CookieContainer(); 
     HttpClientHandler handler = new HttpClientHandler() 
     { 
      CookieContainer = cookieJar 
     }; 
     handler.UseCookies = true; 
     handler.UseDefaultCredentials = false; 
     HttpClient client = new HttpClient(handler as HttpMessageHandler) 
     { 
      BaseAddress = address 
     }; 

     HttpContent content = new StringContent(string.Format("username={0}&password={1}&login=Login&keeplogged=1", username, password)); 
     HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content); 
    } 

我不知道爲什麼這不起作用。當我嘗試.NET 4風格時,它工作正常。

+1

順便說一句:用[FormUrlEncodedContent]代替的StringContent(http://msdn.microsoft.com/en-us/library/system.net.http.formurlencodedcontent(V = vs.110)),與字符串。格式。您的代碼不能正確地轉義用戶名和密碼。 – dtb 2012-07-26 00:42:38

+0

@dtb這就是答案,如果你想發佈它作爲答案,我會接受它。 – Stephen 2012-07-26 00:45:49

回答

7

使用FormUrlEncodedContent而不是StringContentstring.Format。您的代碼不能正確地轉義用戶名和密碼。

HttpContent content = new FormUrlEncodedContent(new[] 
{ 
    new KeyValuePair<string, string>("username", username), 
    new KeyValuePair<string, string>("password", password), 
    new KeyValuePair<string, string>("login", "Login"), 
    new KeyValuePair<string, string>("keeplogged", "1") 
}); 
+0

如何將此cookie傳遞給webview?這樣我可以使用該cookie顯示一個網頁? – 2012-11-20 05:32:05

+0

這也發送信息作爲職位,而不是作爲標題或cookie。我如何將它作爲標頭/ cookie發送? – 2012-11-20 10:04:34

+0

@MilanAggarwal:聽起來像一個很好的問題[問題在StackOverflow.com](http://stackoverflow.com/questions/ask) – dtb 2012-11-20 10:25:56

相關問題