PostAsync에서 쿠키를받지 못한 C # 메트로 HttpClient.
-
11-12-2019 - |
문제
.NET 4.5 HTTPClient를 사용하여 웹 사이트에 로그인하려고 시도하고 쿠키를받습니다.나는 시도를 남기고 cookieContainer를 확인하기 전에 나는 쿠키가 없다.응답은 200 개의 상태를 다시 보냅니다.
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 스타일을 시도 할 때 잘 작동합니다.
해결책
StringContent String.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")
});
. 제휴하지 않습니다 StackOverflow