Felipe A.
Felipe A.

Reputation: 949

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?

Upvotes: 6

Views: 6666

Answers (3)

SHUBHAM SONI
SHUBHAM SONI

Reputation: 111

  Step 1:
public interface ApiConnection {
     @GET("GET_LOCAL/{id}")
        fun colony(@Header("Authorization") authkey:String? ,
                      @Path("id") id:String?): Call<JsonObject> }

 step 2: create static Gloabalmethod 
fun Authpass(): String {
                    var data = ByteArray(0)
                    try {data =(CommonStatic.commonVariable.API_USERNAME + ":" + CommonStatic.commonVariable.API_PASSWORD).toByteArray(
                                charset("UTF-8"))
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }
               return "Basic " + Base64.encodeToString(data, Base64.NO_WRAP)
                }
 Step 3:Retrofit Class
fun getSTP(): ApiCon? {
        val gson: Gson = GsonBuilder()
            .setLenient()
            .create()
        val r: Retrofit = Retrofit.Builder().baseUrl(CommonStatic.commonVariable.BASE_URL_PTS)
            .addConverterFactory(GsonConverterFactory.create(gson)).build()
        return r.create(ApiConnection::class.java)
    }
step 4 : call 


try {
 val call: Call<JsonObject>?=RetrofitCall.retrofit.getSTP()?.colony(GloabalClass.GloabalMethod.Authpass(),id)
 if (call != null) {
       call.enqueue(object : Callback<JsonObject> {
     override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) 
 {
       if (response.isSuccessful) {
        val ward : JsonObject? = response.body()
        val jsonObject = JSONObject(ward.toString())
     val colonyArray: JSONArray = jsonObject.getJSONArray("Result")} else {Toast.makeText(applicationContext, "Failed", Toast.LENGTH_SHORT).show()}}override fun onFailure(call: Call<JsonObject>, t: Throwable) {
  Log.d("loginAuthendication", "failure--" + t.toString())
 Toast.makeText(applicationContext, "NO INTERNET CONNECTION ", Toast.LENGTH_SHORT).show()
                            }
                        }) }
            } catch (e: Exception) {
                Log.d("loginAuthendication", e.toString())
            }

Upvotes: 0

Sukitha Udugamasooriya
Sukitha Udugamasooriya

Reputation: 2308

If you use Retrofit 2 and here is a sample for some basic authentication in headers

public interface SomeApi {
@Headers({
   "Content-Type: application/json",
   "Authorization: Basic KzY1OTY0MjA4NTQ6MTExMTE="
})
@POST("test/someService")
Completable getTrips();

}

Upvotes: 0

Rasoul Miri
Rasoul Miri

Reputation: 12222

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();

Upvotes: 2

Related Questions