我正在尝试使用spring rest模板来做一个post请求来登录。
当我在第一个请求中收到响应时,我存储通过cookie接收的会话id。我在一个set-cookie响应头中检索它,我通过以下方式获得:
//first request
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
LinkedMultiValueMap<String, Object> mvm = new LinkedMultiValueMap<String, Object>();
mvm.add("LoginForm_Login", "login");
mvm.add("LoginForm_Password", "password");
ResponseEntity<String> result = restTemplate.exchange(uriDWLogin, HttpMethod.POST, requestEntity, String.class);
result.getHeaders().get("Set-Cookie").stream().forEach(System.out::println);然后,在每个后续请求中,我使用在第一个请求中收到的值设置Cookie请求头:
//subsequent request
RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders();
headers.set("Cookie",cookies.stream().collect(Collectors.joining(";")));
HttpEntity<String> entity = new HttpEntity<String>(headers);
RestTemplate.exchange("http://url", HttpMethod.POST, entity, String.class);对于第二个请求,一切正常,但我无法为其他请求保留会话
发布于 2015-08-31 19:59:01
您将需要使用某种缓存来存储您的访问令牌。当您要访问下游服务时,您需要从缓存中获取令牌。如果缓存不包含令牌,您将首先对其进行身份验证和检索,并将其存储到缓存中。
缓存始终是一个棘手的话题,因为它必须是线程安全的。我会尽量避免servlet会话。你是在消费服务,而不是被消费。
有多种缓存选项,但由于您已经在使用Spring,spring缓存可能是很好的选择。Take a look at this Spring Cache guide to start.
https://stackoverflow.com/questions/32310471
复制相似问题