This is my recent code:
HttpClient authClient = new HttpClient(); authClient.BaseAddress = new Uri("http://localhost:4999/test_db/_session"); authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var user = new LoginUserSecretModel { name = userKey, password = loginData.Password, }; HttpResponseMessage authenticationResponse = authClient.PostAsJsonAsync("", user).Result;
Procedure. Use the HTTP request object that is passed to the service method of your servlet to get all cookies that the client browser sent with the request. 1. Use the getCookies() method of the HttpServletRequest to retrieve an array of all cookies in the request.
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, you can both create and retrieve cookie values.
Cookies in Web API To add a cookie to an HTTP response, create a CookieHeaderValue instance that represents the cookie. Then call the AddCookies extension method, which is defined in the System.
The issue I have with many of the answers here is that using CookieContainer
uses short-lived HttpClient
objects which is not recommended.
Instead, you can simply read the "Set-Cookie"
header from the response:
// httpClient is long-lived and comes from a IHttpClientFactory HttpResponseMessage response = await httpClient.GetAsync(uri); IEnumerable<string> cookies = response.Headers.SingleOrDefault(header => header.Key == "Set-Cookie")?.Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With