我正在嘗試使用.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風格時,它工作正常。
順便說一句:用[FormUrlEncodedContent]代替的StringContent(http://msdn.microsoft.com/en-us/library/system.net.http.formurlencodedcontent(V = vs.110)),與字符串。格式。您的代碼不能正確地轉義用戶名和密碼。 – dtb 2012-07-26 00:42:38
@dtb這就是答案,如果你想發佈它作爲答案,我會接受它。 – Stephen 2012-07-26 00:45:49