2015-09-04 237 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