nysertxs
nysertxs

Reputation: 73

How to use Authorization Token token=A-123456789qwertyuio12 Header in Retrofit 2.0

im trying to consume an api that has that authorization header, i can get a 200 response in Postman with all data but cant get it to work in retrofit

Upvotes: 1

Views: 815

Answers (2)

DaiDong
DaiDong

Reputation: 41

May be you need add the Token using OkHttp Interceptor.

OkHttpClient client = new OkHttpClient.Builder()
        .addNetworkInterceptor(mTokenInterceptor)
        .build();

then add it to Retrofit:

Retrofit retrofit = new Retrofit.Builder()
        .client(client)
        .baseUrl(base_url)
        .build();

the mTokenInterceptor:

Interceptor mTokenInterceptor = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (mToken != null) {
            Request.Builder requestBuilder = request.newBuilder()
                    .addHeader("Authorization", mToken);
            Request newRequest = requestBuilder.build();

            return chain.proceed(newRequest);
        }
        return chain.proceed(request);

    }
};

when you get the Token, just assign the mToken,

Upvotes: 1

Aniruddha
Aniruddha

Reputation: 4487

You can try something like below, just a crude example

@GET("your server url goes here")
    Call<Your_Model_Class> getServerData(@Header("Authorization") String token);

Pass your token to getServerData method.

Upvotes: 0

Related Questions