반응형
.net 4.5에서 HttpClient를 사용하여 쿠키를 응답에서 벗어나려는 시도
작동으로 작동하는 다음 코드가 있습니다. 응답에서 쿠키를 가져 오는 방법을 알 수 없습니다. 내 목표는 요청에 쿠키를 설정하고 응답에서 쿠키를 수 있기 때문에 원합니다. 생각?
private async Task<string> Login(string username, string password)
{
try
{
string url = "http://app.agelessemail.com/account/login/";
Uri address = new Uri(url);
var postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password ", password)
};
HttpContent content = new FormUrlEncodedContent(postData);
var cookieJar = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false
};
var client = new HttpClient(handler)
{
BaseAddress = address
};
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
return body;
}
catch (Exception e)
{
return e.ToString();
}
}
완전한 대답은 다음과 가변합니다.
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
Uri uri = new Uri(UrlBase);
var responseCookies = cookieJar.GetCookies(uri);
foreach (Cookie cookie in responseCookies)
{
string cookieName = cookie.Name;
string cookieValue = cookie.Value;
}
요청에 쿠키를 추가 구매 구매 전에 쿠키 컨테이너를 CookieContainer.Add(uri, cookie)
. 요청이 모든 준비 후 쿠키 컨테이너는 응답의 쿠키로 자동으로 채워집니다. 그런 다음 GetCookies ()를 호출하여 검색 할 수 있습니다.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync("http://google.com").Result;
Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);
Console.ReadLine();
주어진 URL로 쿠키 값을 쉽게 얻을 수 있습니다.
private async Task<string> GetCookieValue(string url, string cookieName)
{
var cookieContainer = new CookieContainer();
var uri = new Uri(url);
using (var httpClientHandler = new HttpClientHandler
{
CookieContainer = cookieContainer
})
{
using (var httpClient = new HttpClient(httpClientHandler))
{
await httpClient.GetAsync(uri);
var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
return cookie?.Value;
}
}
}
반응형
'IT' 카테고리의 다른 글
Contains (string) 대신 LINQ Contains (string [])를 사용하는 방법 (0) | 2020.09.01 |
---|---|
Vagrant의 신용 링크 및 동기화 된 폴더 (0) | 2020.09.01 |
Collections.emptyList ()와 Collections.EMPTY_LIST의 차이점은 무엇입니까? (0) | 2020.09.01 |
((a + (b & 255)) & 255)는 ((a + b) & 255)와 같은가요? (0) | 2020.09.01 |
CFLAGS 대 CPPFLAGS (0) | 2020.09.01 |