【问题标题】:How can i make a Http Post request to external Rest Api? [closed]如何向外部 Rest Api 发出 Http Post 请求? [关闭]
【发布时间】:2024-01-03 19:15:01
【问题描述】:

我是 Java spring 框架的新手, 我需要一种从我的应用程序调用外部 Rest Api 的方法。 是否有任何“最佳实践”http 客户端,以便我可以根据需要使用?

提前致谢

【问题讨论】:

标签: java spring api spring-boot httpclient


【解决方案1】:

使用 RestTemplate:

@RestController
public class SampleController {
   @Autowired
   RestTemplate restTemplate;

   @RequestMapping(value = "/sample/endpoint", method = RequestMethod.POST)
   public String createProducts(@RequestBody SampleClass sampleClass) {
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity<SampleClass> entity = new HttpEntity<SampleClass>(sampleClass,headers);

      return restTemplate.exchange(
         "https://example.com/endpoint", HttpMethod.POST, entity, String.class).getBody();
   }
}

【讨论】:

  • 我建议始终将导入添加到此类解决方案中。