我如何向外部Rest Api发出Http Post请求?

时间:2019-02-13 08:42:36

标签: java spring api spring-boot httpclient

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

预先感谢

1 个答案:

答案 0 :(得分:2)

使用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<Product> entity = new HttpEntity<SampleClass>(sampleClass,headers);

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