2

i am new in Java spring Framework , i need a way to call from my application an external Rest Api. Is there any 'best practice' http client so i can use for my need?

Thanks in Advance

billy tzez
  • 155
  • 1
  • 2
  • 11
  • 7
    [RestTemplate](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html) maybe? – dbl Feb 13 '19 at 08:44
  • 3
    https://stackoverflow.com/questions/42365266/call-another-rest-api-from-my-server-in-spring-boot – luk2302 Feb 13 '19 at 08:46
  • [This tutorial](https://spring.io/guides/gs/spring-boot/) should help. – Benoit Feb 13 '19 at 08:46
  • 1
    Please, do some google work, before asking any question to the community. For example, you can search for: "spring perform post request" in google and you definitely will find some great answer on SF. – Vüsal Feb 13 '19 at 08:58
  • 1
    https://www.google.com/search?q=spring+resttemplate = 336.000 results – Stefan Feb 13 '19 at 08:59
  • 3
    Possible duplicate of [Call another rest api from my server in Spring-Boot](https://stackoverflow.com/questions/42365266/call-another-rest-api-from-my-server-in-spring-boot) – Vüsal Feb 13 '19 at 08:59
  • use RestTemplate provided by spring itself it will improve your application performance as well – Ganesh Gudghe Feb 13 '19 at 09:12

1 Answers1

5

Use 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();
   }
}
Thanthu
  • 4,399
  • 34
  • 43