Asynchronous REST calls using Retrofit2

In this article we will learn how to make an asynchronous REST call using Retrofit2.

Overview

Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to define how requests are made

Code

Add the below two dependencies in your pom.xml file.

<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>retrofit</artifactId>
    <version>2.4.0</version>
</dependency>
<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>converter-jackson</artifactId>
    <version>2.4.0</version>
</dependency>

Now define the REST service interface as below:

private interface RestService {

    @POST("create")
    Call<User> createUser(@Body User user);
}

Now lets create the service implementation using the base URL:

final RestService restService = new Retrofit.Builder()
        .baseUrl("http://dummy.restapiexample.com/api/v1/")
        .addConverterFactory(JacksonConverterFactory.create())
        .build()
        .create(RestService.class);

We will make use of the enqueue() method to do the asynchronous call. Using asynchronous requests forces you to implement a Callback with its two callback methods: onResponse() and onFailure. When calling the asynchronous createUser() method from a service class, you have to implement a new Callback and define what should be done once the request finishes. The following code snippet illustrates an exemplary implementation.

restService.createUser(new User("My name", "54321", "99")).enqueue(new Callback<User>() {
    public void onResponse(Call<User> call, Response<User> response) {
        System.out.println("Response: " + response);
    }

    public void onFailure(Call<User> call, Throwable throwable) {
        System.err.println("ERROR:" + throwable.getMessage());
    }
});

Conclusion

In this example we saw how to make an asynchronous REST call using Retrofit2. For the full source code please refer to retrofit-async-example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: