0

I am using retrofit2 to logout in App but everytime it gives error406 : Not Acceptable : User is not logged in. . i am using retrofit custom header authentication . Here is my Code :

logout code

public void logout()

{ Log.v("checkTokenbefore",Constants.token);

  OkHttpClient httpClient1 = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Interceptor.Chain chain) throws IOException {
          Request original = chain.request();
            Log.v("checkLogin",Constants.token+Constants.username+Constants.password) ;
          // Request customization: add request headers
          Request.Builder requestBuilder = original.newBuilder()
                  .addHeader("Accept-Language","application/json").addHeader("content-type", "application/x-www-form-urlencoded")
                  .addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")


                  .addHeader("X-CSRF-Token",Constants.token)


                  ;

          Request request = requestBuilder.method(original.method(),original.body()).build();
          return chain.proceed(request);
      }
  }).build();

  Retrofit retrofit1 = new Retrofit.Builder()
          .baseUrl(Constants.API_BASE_URL)
          .client(httpClient1)

          .addConverterFactory(GsonConverterFactory.create())
          .build();

  ApiInterface restAPI1 = retrofit1.create(ApiInterface.class);

  Call<Logout> callLogout = restAPI1.userLogout(Constants.token,Constants.username,Constants.password);
  callLogout.enqueue(new Callback<Logout>() {
      @Override
      public void onResponse(Call<Logout> call, retrofit2.Response<Logout> response) {
          Log.v("responseLogout",response.code()+"code"+response.errorBody().toString()+response.message()) ;
      }

      @Override
      public void onFailure(Call<Logout> call, Throwable t) {

      }
  });

}

While Following is the code for login which works fine :

 public void loginQuestin(){

    //checkValidation ();
/*
    ApiInterface apiService =
            ApiClient.create(ApiInterface.class) ;*/
    ApiInterface restAPI = retrofit.create(ApiInterface.class);

    Call<UserAgain> call = restAPI.userLogin(mEmailAddress.getText().toString().trim(),
            mPassword.getText().toString().trim());
    call.enqueue(new Callback<UserAgain>() {
      @Override
      public void onResponse(Call<UserAgain> call, Response<UserAgain> response) {
        Log.v("check",response.code()+"login"+response.body().getToken()) ;
         //response.body().getU
          Constants.username = mEmailAddress.getText().toString().trim() ;
          Constants.password =  mPassword.getText().toString().trim() ;

          if (response.code()==200) {
            Log.v("checkAgain",response.code()+"login") ;
           Constants.token = response.body().getToken() ;
            startActivity(new Intent(LoginActivity.this, NavigationDrawerActivity.class));
          }
      }

      @Override
      public void onFailure(Call<UserAgain> call, Throwable t) {
        Log.v("check","failed");
        t.printStackTrace();
      }
    });
  }

//API/Http client for login api call

public class ApiClient {

   public static OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            // Request customization: add request headers
            Request.Builder requestBuilder = original.newBuilder() .addHeader("Accept-Language","application/json")
                    .addHeader("content-type", "application/x-www-form-urlencoded").addHeader("API_KEY", "a5XSE8XCdsY6hAoCNojYBQ")

                    ;

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    }).build();



    public static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.API_BASE_URL)
            .client(httpClient)

            .addConverterFactory(GsonConverterFactory.create())
            .build();
   public static ApiInterface restAPI = retrofit.create(ApiInterface.class);
}

API Interface class

@POST("token")
Call<Token> getToken();


@FormUrlEncoded
@POST("login")
Call<UserAgain> userLogin(@Field("username") String param1, @Field("password") String param2);

@FormUrlEncoded
@POST("logout")
Call<Logout> userLogout(@Field("username") String param1 , @Field("password") String param2);

Login APi works fine give a response code of 200 OK . The major issue is encountered when working with added dynamic customn header on logout api (client xsrf token )

Reference : https://futurestud.io/tutorials/retrofit-add-custom-request-header api formats :

User Authentication/Login

Purpose: - User Login Rest URL: - /api/v1/people/login Method:-POST Headers: Accept-Language: application/json API_KEY: a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded X-CSRF-Token:

User Logout

Purpose: - User Logout Rest URL: - /api/v1/people/logout Method:-POST Headers: Accept-Language: application/json API_KEY: a5XSE8XCdsY6hAoCNojYBQ Content-Type: application/x-www-form-urlencoded X-CSRF-Token: Parameters in body: username: e.g service@test.com password: e.g. 123456

Naman
  • 39
  • 11

1 Answers1

0

Use Interceptors for adding dynamic Header.

httpClient.addInterceptor((Interceptor.Chain chain) -> {
            Request originalRequest = chain.request();

set OAuth token

Request.Builder newRequest = originalRequest.newBuilder();

newRequest.header("Authorization", accessToken).method(originalRequest.method(), originalRequest.body());

originalRequest = newRequest.build();
chain.proceed(originalRequest); 

repeat request with new token

Response response = chain.proceed(originalRequest); //perform request, here original request will be executed

  if (response.code() == 401) {
            //if unauthorized
            //perform all 401 in sync blocks

      }
      return chain.proceed(newRequest.build());
});
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
Nimisha V
  • 461
  • 4
  • 12
  • I guess I have used the same thing reference link : https://futurestud.io/tutorials/retrofit-add-custom-request-header – Naman Jun 06 '17 at 11:28
  • I guess there is some issue with XSRF token I am using , beacuse without that the api calls work – Naman Jun 07 '17 at 12:52