我创建了一个微服务,其端点为
http://www.example.com/create
发出一个发布请求。在此请求中,我使用 ResponseEntity
类,即
@PostMapping("/create")
public ResponseEntity<?> createUser(@RequestBody User user) {
//do some other stuff i.e. validation
someService.createUser(user);
URI location = ...;
return ResponseEntity.created(location).build();
}
现在我想从另一个应用程序调用发布请求/create
,即在访问http://www.example-2.com/signup
时调用/create
创建用户实体。
@PostMapping("/signup")
public ModelAndView createUser(@Valid UserForm form) {
//How do I make `/create` post request to post
//the `form` entity
return new ModelAndView("some view");
}
最佳答案
使用 Spring RestTemplate 。这是tutorial example关于如何使用它。您只需在 Controller 类中创建一个 RestTemplate 和 Autowiring 的单例 bean,然后使用它来进行其余调用。
String response = restTemplate.postForObject("https://your-domain/create",user, String.class)
关于java - 如何执行来自另一个应用程序的发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063682/