2015-09-04 238 views
4

我试图用弹簧安置模板做一个POST请求的登录。春RestTemplate重定向302

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); 

我ResponseEntity状态是302,我想按照这个要求来获取身体的反应,因为我没有得到这个请求的正文。

18:59:59.170 MAIN [http-nio-8080-exec-83] DEBUG c.d.s.c.DemandwareCtlr - loginToSandbox - StatusResponse - 302 
18:59:59.170 MAIN [http-nio-8080-exec-83] DEBUG c.d.s.c.DemandwareCtlr - loginToSandbox - BodyResponse - 

我该怎么做才能解决这个问题?

回答

9

如果请求是GET请求,则自动执行重定向(请参阅this answer)。为了做到这一点的POST请求,一个选择可能是使用不同的要求在工厂,像HttpComponentsClientHttpRequestFactory,并将其设置为使用与所需设置的HttpClient跟随重定向(见LaxRedirectStrategy):

final RestTemplate restTemplate = new RestTemplate(); 
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); 
final HttpClient httpClient = HttpClientBuilder.create() 
               .setRedirectStrategy(new LaxRedirectStrategy()) 
               .build(); 
factory.setHttpClient(httpClient); 
restTemplate.setRequestFactory(factory); 

我还没有测试,但这应该工作。

+0

Tks为您的帮助,它的工作原理,现在我需要得到“Cookie”而不是“Set-cookie”,我该怎么做? – Aliyon

+1

只需从头文件中获取“Set-Cookie”,就像使用Cookie,result.getHeaders()。get(“Set-Cookie”)。get(0).split(“;”)[0]; – chrismarx