Retrofit2 Authorization - Global Interceptor for access token

前端 未结 5 1340
我在风中等你
我在风中等你 2020-12-22 23:24

I\'m trying to use Retrofit2, I want to add Token to my Header Like this:

Authorization: Bearer Token but the <

5条回答
  •  半阙折子戏
    2020-12-23 00:19

    If you want to add Bearer Token as a Header you can do those types of process.

    This is one way to work with Bearer Token

    In your Interface

    @Headers({ "Content-Type: application/json;charset=UTF-8"})
    @GET("api/Profiles/GetProfile")
    Call getUser(@Query("id") String id, @Header("Authorization") String auth);
    

    After that you will call the Retrofit object in this way

    Retrofit retrofit  = new Retrofit.Builder()
                        .baseUrl("your Base URL")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
    
    APIService client = retrofit.create(APIService.class);
    Call calltargetResponse = client.getUser("0034", "Bearer "+token);
    calltargetResponse.enqueue(new Callback() {
           @Override
           public void onResponse(Call call, retrofit2.Response response) {
               UserProfile UserResponse = response.body();
               Toast.makeText(this, " "+response.body(), Toast.LENGTH_SHORT).show();
                    }
            @Override
            public void onFailure(Call call, Throwable t) {
                //Toast.makeText(this, "Failed ", Toast.LENGTH_SHORT).show();
            }
    });
    

    Another Way is using intercept, which is similar the previous Answer. But, that time you just need to modify interface little bit like.

    @Headers({ "Content-Type: application/json;charset=UTF-8"})
    @GET("api/Profiles/GetProfile")
    Call getUser(@Query("id") String id); 
    

    Hope this will work for you.

提交回复
热议问题