Home > OS >  Spotify API - Client Credentials Flow in Kotlin with Retrofit doesnt work
Spotify API - Client Credentials Flow in Kotlin with Retrofit doesnt work

Time:08-29

I am trying to use Spotify API. To use the API i need to get a new auth token. So per their guides enter image description here

this is my API interface

@FormUrlEncoded
    @POST("api/token")
    fun getToken(@Header("Authorization") auth:String,
                 @Header("Content-Type") content :String,
                 @Field(("grant_type")) grantType:String ): Call<Token>

this is my MainActivity:

val retrofit: Retrofit = Retrofit.Builder().baseUrl(TOKEN_URL)
            .addConverterFactory(GsonConverterFactory.create()).build()
        val service :TopTrackApi = retrofit.create(TopTrackApi::class.java)

        val base64String = "Basic "    get64BaseString("6bcfc9a9fccd45c8b9bb9c980f03e653:96c65e1824084adfb1ae99ef97734621")

        Log.i("64Base ", base64String)
        val listCall : Call<Token> = service.getToken(base64String,"application/x-www-form-urlencode","client_credentials")

        listCall.enqueue(object : Callback<Token>{
            override fun onResponse(response: Response<Token>?, retrofit: Retrofit?) {
                if (response?.body() != null) {
                Log.i("Response!", response.body().access_token)
                }
                if(response?.body() == null){
                    Log.i("Response!", "null response body")
                }
            }
            override fun onFailure(t: Throwable?) {
                Log.e("Error", t!!.message.toString())
            }
        })

fun get64BaseString(value:String):String{
        return Base64.encodeToString(value.toByteArray(),Base64.NO_WRAP)
    }

This is the token class as per their json object: enter image description here

data class Token(
    val access_token: String,
    val expires_in: Int,
    val token_type: String
)

As a result I get this in Logcat:

I/Response: null response body

edit:When i am running the same values in a curl command it works(it returns the json object)

What am I doing incorrect? Thanks in advance.

CodePudding user response:

I think your API interface should look like this:

@Headers("Content-Type: application/x-www-form-urlencoded")
@POST("api/token")
    fun getToken(@Header("Authorization") auth:String,
                 @Field(("grant_type")) grantType:String ): Call<Token>

CodePudding user response:

val base64String = "Basic "  get64BaseString("6bcfc9a9fccd45c8b9bb9c980f03e653:96c65e1824084adfb1ae99ef97734621")

I think you are missing basic keyword . You need to add it as prefix to base 64 endcoded client id and secret. There are several authorization types in HTTP for Authorization Header. Since spotify uses Basic Auth, you need to specify it.

  • Related