Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate redirect 302

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

like image 539
Aliyon Avatar asked Sep 04 '15 07:09

Aliyon


Video Answer


1 Answers

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.

like image 148
Nicolas Avatar answered Nov 27 '22 00:11

Nicolas