How can the expiration time of cookies be configured in RestTemplate?
RestTemplate does not have a direct method to set the expiration time of a cookie. Generally, the expiration time of a cookie is set by the server and specified in the response header with Set-Cookie. The client only needs to store the cookie and include it in the request header for future requests.
If you need to manually set the expiration period of a cookie, you can do so by following these steps:
- Create a Cookie object and establish its expiration time.
Cookie cookie = new Cookie("cookieName", "cookieValue");
cookie.setMaxAge(3600); // 设置有效期为1小时
- Save the Cookie to the header of the RestTemplate request.
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Cookie", cookie.getName() + "=" + cookie.getValue());
return execution.execute(request, body);
});
- When sending a request, RestTemplate will send the request header containing the cookie to the server side.
It is important to note that manually setting the expiration date of cookies may be overridden by the server, so it is recommended to set the expiration date of cookies on the server side.