Retrofit + Basic Authentication
I have implemented an upgrade with basic authentication, I send @header to my login request, but when I call some authenticated request, it returns me 401 (not authorized).
How do I implement it? Or do 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 modified 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 anyone help me?
+3
source to share
2 answers