java - 如何执行来自另一个应用程序的发布请求

标签 java spring spring-boot

我创建了一个微服务,其端点为 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/

相关文章:

java - Retrofit2 如何获取重定向网址 @HEAD ("/")

java - 使用 SBT 构建工具在 Java 中编译 Protobufs 时出现编译错误

java - 即使设置了 spring.expression.compiler.mode,Spring SpEL 也不会编译

java - 如何使用 :switch and th:each 处理 thymeleaf 中的两个列表

java - 当我构建maven单元测试时,出现以下错误

java - 在两个 Activity 之间切换而不丢失数据

java - 文本查询匹配(棘手)

java - 如何将 Eclipse Java SE 应用程序转换为 J2E 应用程序?

java - Hibernate Session 未使用 AOP 切点事务管理器绑定(bind)到线程

java - Spring boot @ConfigurationProperties 未加载