Get OAuth 2.0 access token using Retrofit 2.x

Retrofit is an awesome and easy to use library. You can use Retrofit for any Android or Java application which need to interact with our OAuth2.0 server to get access token.

You just need to build the retrofit properly to get it done. It doesn’t require any advance knowledge. Let’s see how it can be done easily.

To get the access token using Retrofit we need to do –

Add Retrofit in your project via Maven or Gradle. Complete installation guide can be found here.

Now let’s create the Retrofit builder. And before doing that we need to create a service interface.

//AccessTokenServiceInterface.java
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface AccessTokenServiceInterface {

    @POST("/oauth/v1/access_token")
    @FormUrlEncoded
    Call<TokenResponse> getToken(@Field("client_id") String client_id, @Field("client_secret") String client_secret, @Field("scope") String scope, @Field("grant_type") String grant_type);
}

And now the builder.

//Http.java
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;

public class Http {
    public static void main(String[] args) {
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://myaccount.previewtechs.com")
                .build();

        AccessTokenServiceInterface service = retrofit.create(AccessTokenServiceInterface.class);

        //grant types = client_credentials
        Call<TokenResponse> call = service.getToken("OAUTH CLIENT ID", "OAUTH CLIENT SECRET", "basic email", "client_credentials");
        try {
            Response<TokenResponse> response = call.execute();
            System.out.println(response.body().getAccessToken());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And also we need to map the JSON response from our OAuth 2.0 server. So we need a model to map that. Let’s create TokenResponse.java model class

//TokenResponse.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class TokenResponse {

    @SerializedName("token_type")
    @Expose
    private String tokenType;
    @SerializedName("expires_in")
    @Expose
    private Integer expiresIn;
    @SerializedName("access_token")
    @Expose
    private String accessToken;

    public String getTokenType() {
        return tokenType;
    }

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public Integer getExpiresIn() {
        return expiresIn;
    }

    public void setExpiresIn(Integer expiresIn) {
        this.expiresIn = expiresIn;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

}

Now run Http.main and you will get your access token.

That’s it. Now run the Http.main and you will get the access token easily. Download these scripts from our¬†PreviewTechnologies/access-token-retrofit¬†GitHub repository.

This article also available on our support portal.