Call another rest api from my server in Spring-Boot

前端 未结 5 1475
北恋
北恋 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:37

    Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

    In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

    @Configuration
    public class RestTemplateConfig {
    
        @Bean
        public RestTemplate restTemplate(RestTemplateBuilder builder) {
           return builder.build();
        }
    }
    

    Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

    @Autowired
    private RestTemplate restTemplate;
    

    Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

    ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
        URL, 
        HttpMethod.GET, 
        null, 
        new ParameterizedTypeReference<List<POJO>>() {
        });
    List<POJO> pojoObjList = responseEntity.getBody();
    

    Happy Coding :)

    0 讨论(0)
  • 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<String> entity=new HttpEntity<String>(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

    0 讨论(0)
  • 2020-12-01 01:46

    This website has some nice examples for using spring's RestTemplate. Here is a code example of how it can work to get a simple object:

    private static void getEmployees()
    {
        final String uri = "http://localhost:8080/springrestexample/employees.xml";
    
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(uri, String.class);
    
        System.out.println(result);
    }
    
    0 讨论(0)
  • 2020-12-01 01:47

    Does Retrofit have any method to achieve this? If not, how I can do that?

    YES

    Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

    For more information refer the following link

    https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

    0 讨论(0)
  • 2020-12-01 01:50

    Modern Spring 5+ answer using WebClient instead of RestTemplate.

    Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).

    @Bean
    public WebClient localApiClient() {
        return WebClient.create("http://localhost:8080/api/v3");
    }
    

    Inject and use the bean from your service(s).

    @Service
    public class UserService {
    
        private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);
    
        private final WebClient localApiClient;
    
        @Autowired
        public UserService(WebClient localApiClient) {
            this.localApiClient = localApiClient;
        }
    
        public User getUser(long id) {
            return localApiClient
                    .get()
                    .uri("/users/" + id)
                    .retrieve()
                    .bodyToMono(User.class)
                    .block(REQUEST_TIMEOUT);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题