retrofit “Authorization”, “Bearer ”+ token

2019-03-09 07:33发布

问题:

I'm trying to use Retrofit (2), i want to add Token to my Header Like this:
Authorization: Bearer Token but the code below doesn't work:

public interface APIService {

        @Headers({
                    "Authorization", "Bearer "+ token
            })

    @GET("api/Profiles/GetProfile?id={id}")
    Call<UserProfile> getUser(@Path("id") String id);
}

my server is asp.net webApi please help what should i do?

回答1:

You have two choices -- you can add it as a parameter to your call --

@GET("api/Profiles/GetProfile?id={id}")
Call<UserProfile> getUser(@Path("id") String id, @Header("Authorization") String authHeader);

This can be a bit annoying because you will have to pass in the "Bearer" + token on each call. This is suitable if you don't have very many calls that require the token.

If you want to add the header to all requests, you can use an okhttp interceptor --

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Chain chain) throws IOException {
        Request newRequest  = chain.request().newBuilder()
            .addHeader("Authorization", "Bearer " + token)
            .build();
        return chain.proceed(newRequest);
      }
    }).build();

Retrofit retrofit = new Retrofit.Builder()
    .client(client)
    .baseUrl(/** your url **/)
    .addConverterFactory(GsonConverterFactory.create())
    .build();


回答2:

if you want to add Bearer Token as a Header you can do those types of process.. This is One Way to work with Bearar Token

In your Interface

@Headers({ "Content-Type: application/json;charset=UTF-8"})
    @GET("api/Profiles/GetProfile")
    Call<UserProfile> 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<UserProfile> calltargetResponce = client.getUser("0034", "Bearer "+token);
        calltargetResponce.enqueue(new Callback<UserProfile>() {
            @Override
            public void onResponse(Call<UserProfile> call, retrofit2.Response<UserProfile> response) {
                UserProfile UserResponse = response.body();
                Toast.makeText(this, " "+response.body(), Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFailure(Call<UserProfile> call, Throwable t) {
                //Toast.makeText(this, "Failed ", Toast.LENGTH_SHORT).show();
            }
        });

Another Way is using intercept... which is similar the previous Answaer 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<UserProfile> getUser(@Query("id") String id); 

Hope this will work for you