11

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 ?!

Aliyon
  • 149
  • 3
  • 3
  • 9

1 Answers1

30

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.

Community
  • 1
  • 1
Nicolas
  • 2,151
  • 1
  • 25
  • 29
  • Tks for your help, it works, now i need to get the "Cookie" not the "Set-cookie", how i could do it ? – Aliyon Sep 04 '15 at 12:12
  • 1
    just get the "Set-Cookie" from the headers, just like you would with cookie, result.getHeaders().get("Set-Cookie").get(0).split(";")[0]; – chrismarx Nov 24 '15 at 16:50
  • 1
    If org.apache.httpcomponents:httpclient is on the classpath, the behaviour of RestTemplate is different - it does not follow redirects on GETs (with the default constructor). – Mateusz Stefek Jul 31 '18 at 09:55
  • 1
    `SimpleClientHttpRequestFactory` doesn't follow redirectS it follows redirecT. Only one. – Skeeve Nov 09 '18 at 14:48