nysertxs nysertxs - 2 months ago 26
reST (reStructuredText) Question

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

Answer

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("Token", mToken);
            Request newRequest = requestBuilder.build();

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

    }
};

when you get the Token, just assign the mToken,