Search code examples
androidkotlinretrofitgithub-api

Cannot add GitHub API header "Authorization token" to GET request in Retrofit2


GitHub APi documentation says that I need to pass access token in header. enter image description here

This command works fine for me with replacing OAUTH_TOKEN to mine. I try to do the same in code:

    @GET("/user/repos")
    fun getAllUserRepos(
        @Header("Authorization: token") accessToken: String
    ): Call<List<RepoJson>>

But when I get error in enqueque onFailure: Unexpected char 0x20 at 14 in header name: Authorization: token. Then I remove space remove space between Authorization: and token in header and get Unauthorized message from responce in onResponce.

I tried this (also with space between Authorization: and token in header):

    @Headers("Authorization: token MY_VALID_TOKEN")
    @GET("/user/repos")
    fun getAllUserRepos(): Call<List<RepoJson>>

And it executed successfully (through enqueue).

My API:

val api: GiHubApi = Retrofit.Builder()
            .baseUrl("https://api.github.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(GitHubApi::class.java)

Solution

  • As per doc, key="Authorization" and value="token VALID_TOKEN"

    In the Retrofit, you need to pass the key to @GET. But you're passing "Authorization: token"

    So you need to do it like this.

    @GET("/user/repos")
        fun getAllUserRepos(
            @Header("Authorization") accessToken: String
        ): Call<List<RepoJson>>
    

    Call

    getAllUserRepos("token $VALID_TOKEN")