Spring RestTemplate redirect 302

Aliyon picture Aliyon · Sep 4, 2015 · Viewed 22k times · Source

I'm trying to use spring rest template to do a post request to login in.

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

My ResponseEntity status is 302, i want to follow this request to get the body response , because i didn't get the body for this request.

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 - 

What can I do to solve this problem ?!

Answer

Nicolas picture Nicolas · Sep 4, 2015

The redirection is followed automatically if the request is a GET request (see this answer). To make it happen on POST requests, one option might be to use a different request factory, like HttpComponentsClientHttpRequestFactory, and set it to use an HttpClient with the required settings to follow the redirect (see 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);

I haven't tested, but this should work.