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.

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface AccessTokenServiceInterface {

    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.

import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class Http {
    public static void main(String[] args) {
        Retrofit retrofit = new Retrofit.Builder()

        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();
        } catch (IOException e) {

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 model class


public class TokenResponse {

    private String tokenType;
    private Integer expiresIn;
    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.