Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit + Basic Authentication

I've implemented retrofit with basic authentication, I send the @header on my login request but when i call some authenticated request it returns me 401 (Not authorizated).

How I implement it generic? Or i always need to call my authenticated requests with @header?

@GET("user")
Call<User> getUserByEmail(@Query("email") String email, @Header("Authorization") String authorization);

When i call Get User By Email (I authenticate the user)...

@PUT("usuario/{userId}/")
Call<User> putUserById(@Path("userId") Integer id, @Body User user);

When i call Put user ( i need to make an authenticated request).

My retrofit class...

public class NetworkService {
private NetworkAPI networkAPI;
private OkHttpClient okHttpClient;

public NetworkService() {
    okHttpClient = buildClient();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BuildConfig.HOST)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    networkAPI = retrofit.create(NetworkAPI.class);
}

public NetworkAPI getAPI() {
    return networkAPI;
}

private OkHttpClient buildClient() {

    OkHttpClient.Builder builder = new OkHttpClient.Builder();

    builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());

            return response;
        }
    });

    builder.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //this is where we will add whatever we want to our request headers.
            Request request = chain.request().newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json")
                    .build();
            return chain.proceed(request);
        }
    });

    return builder.build();
}
}

Can someone help me?

like image 960
Felipe A. Avatar asked Jul 19 '17 12:07

Felipe A.


1 Answers

use @Header("Authorization") String authorization in NetworkService

 Request request = chain.request().newBuilder()
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "AuthorizationValue")
                    .build();
like image 55
Rasoul Miri Avatar answered Oct 04 '22 03:10

Rasoul Miri