Call another rest api from my server in Spring-Boot

前端 未结 5 1494
北恋
北恋 2020-12-01 01:30

I want to call another web-api from my backend on a specific request of user. For example, I want to call Google FCM send message api to send a message to a

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 01:42

    Create Bean for Rest Template to auto wiring the Rest Template object.

    @SpringBootApplication
    public class ChatAppApplication {
    
        @Bean
        public RestTemplate getRestTemplate(){
            return new RestTemplate();
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ChatAppApplication.class, args);
        }
    
    }
    

    Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.

    @RequestMapping(value = "/postdata",method = RequestMethod.POST)
        public String PostData(){
    
           return "{\n" +
                   "   \"value\":\"4\",\n" +
                   "   \"name\":\"David\"\n" +
                   "}";
        }
    
        @RequestMapping(value = "/post")
        public String getPostResponse(){
            HttpHeaders headers=new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            HttpEntity entity=new HttpEntity(headers);
            return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
        }
    

    Refer this tutorial[1]

    [1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

提交回复
热议问题