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 specific user on an event.
Does Retrofit have any method to achieve this? If not, how I can do that?
Spring boot supports calling one rest service to another rest service using the RestTemplate class. RestTemplate is a synchronised client side class that is responsible for calling another rest service. RestTemplate supports all HTTP methods such as GET, POST, DELET, PUT, HEAD, etc.
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); }
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With