如何向外部 Rest Api 发出 Http Post 请求? [关闭]

Posted

技术标签:

【中文标题】如何向外部 Rest Api 发出 Http Post 请求? [关闭]【英文标题】:How can i make a Http Post request to external Rest Api? [closed] 【发布时间】:2019-07-07 00:42:11 【问题描述】:

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

提前致谢

【问题讨论】:

RestTemplate 也许? ***.com/questions/42365266/… 请先做一些谷歌工作,然后再向社区提问。例如,你可以在谷歌中搜索:“spring perform post request”,你肯定会在 SF 上找到一些很好的答案。 google.com/search?q=spring+resttemplate = 336.000 个结果 Call another rest api from my server in Spring-Boot的可能重复 【参考方案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();
   

【讨论】:

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

以上是关于如何向外部 Rest Api 发出 Http Post 请求? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章