Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly forward POST request from one web application to another in Spring Boot?

Let's consider situation where I have two web application A and B

Initial data comes to A, where I have next controller:

@RestController
public class restController {
@RequestMapping(path = "/testA", method = RequestMethod.POST)
public final void test(*inputdata*) { "redirect POST to B app" }
}

This data must be sent to app B:

@RestController
public class restController {
@RequestMapping(path = "/testB", method = RequestMethod.POST)
public final void test(*inputdata*) { 'some logic' }
}

And result of logic must be sent back to A app.

Communication must happens in RESTful format.

As far as I found out by "googling" there is no way to do it by Spring and I must create custom "POST" method, is that true ? Because this link http://www.baeldung.com/spring-redirect-and-forward contains information about "Redirecting an HTTP POST Request" But I can't get the way they used it.

Thank you!

like image 347
Alfred Moon Avatar asked Apr 19 '18 04:04

Alfred Moon


2 Answers

A redirect goes to the users browser and then goes to the redirected URL. It will always go as a GET request. In your case you will have to call app B from A using a httpclient (RestTemplate) from A. I am not sure whether that will satisfy your requirement. A

Another way could be to send a page as response from the A request and have the page submit a ajax request which is a POST to be, but I guess since you want everything on REST this may not be what you want.

like image 98
Mohit Mutha Avatar answered Oct 13 '22 08:10

Mohit Mutha


You can use RestTemplate or Feign Client.

RestTemplate post example :

Foo foo = restTemplate.postForObject("/testB", request, Foo.class);

However, as you are using Microservices, you should use Feign client for microservices communication.


Edit :

Feign provides many extra benefits over RestTemplate.

Example: Feign client provides load balancing out of the box.

You can read more here

like image 37
Mehraj Malik Avatar answered Oct 13 '22 10:10

Mehraj Malik