0

I've created a GET service to redirect to a webpage that uses POST. I'm trying to use restTemplate because with this I can send the body and header that request the service and I've achieved to get the information that a I need from the service.

However, I need to redirect to the server that has the POST service, but I couldn't, because I don't know how can a set the status code which I redirect to another server.

These are the functions that I'm using:

RequestEntity<Object> req = new RequestEntity<Object>(body, httpHeaders, HttpMethod.POST, url);

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, req, String.class);
Tom
  • 16,842
  • 17
  • 45
  • 54
Robcruzd
  • 21
  • 7
  • Could you share the code of your GET and POST? I didn't understanf what for you are using restTemplate for this case. Redirecting can be performed simply with using the `HttpServletResponse ` in your contoller method. Check this answer, maybe it will help: https://stackoverflow.com/questions/29085295/spring-mvc-restcontroller-and-redirect – Ilya Lysenko Mar 12 '20 at 22:54
  • Does this answer your question: https://stackoverflow.com/questions/29418583/follow-302-redirect-using-spring-resttemplate – Brooklyn99 Mar 13 '20 at 04:43

1 Answers1

0

You could do something like this as http post are not redirected automatically in spring. So the following might help:

 public ResponseEntity<String> getData() {
 final RestTemplate restTemplate = new RestTemplate();
 String url = "http://localhost:8080/my-sample-post-url";
 final HttpComponentsClientHttpRequestFactory factory =
     new HttpComponentsClientHttpRequestFactory();

 final HttpClient httpClient = HttpClientBuilder.create()
     .setRedirectStrategy(new LaxRedirectStrategy()).build();       
     //org.apache.httpcomponents 
 factory.setHttpClient(httpClient);
 restTemplate.setRequestFactory(factory);

 Map<String, String> params = new HashMap<String, String>();
 ResponseEntity<String> response = restTemplate.postForEntity(url,params,String.class);
 if(response.getStatusCode().equals(HttpStatus.OK)) {
   return new ResponseEntity<String>(HttpStatus.SEE_OTHER);
 }
 else {
    return new ResponseEntity(HttpStatus.NOT_FOUND); // for example only
 }
 
 }

Note: Lax RedirectStrategy implementation that automatically redirects all HEAD, GET, POST, and DELETE requests. This strategy relaxes restrictions on automatic redirection of POST methods imposed by the HTTP specification. More here

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
Brooklyn99
  • 987
  • 13
  • 24