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

e4eetjau  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(56)

已关闭。此问题需要更多focused。目前不接受回答。
**要改进此问题吗?**更新此问题,使其仅针对editing this post的一个问题。

4年前关闭。
Improve this question
我是Java spring框架的新手,我需要一种方法从我的应用程序调用外部Rest API。有没有什么“最佳实践”http客户端可以满足我的需要?

4uqofj5v

4uqofj5v1#

使用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();
   }
}

字符串

相关问题