如何在Retrofit2中添加请求头?SharedPreference Token问题求助
Let’s tackle your problem head-on. You’re running into two main issues here: your SharedPrefManager instance is null when trying to fetch the Token, and your Retrofit client isn’t automatically adding the Token to request headers. Here’s how to fix both:
Step 1: Fix SharedPrefManager Initialization
In your original RetrofitClient code, you declared SharedPrefManager sharedPrefManager; but never initialized it—this is exactly why the object is null. You need to properly instantiate it, usually by passing a Context (since SharedPreferences relies on it to access app storage).
Assuming your SharedPrefManager uses a singleton pattern (the standard approach for shared preference managers), update your getClient method to accept a Context parameter and initialize the manager correctly.
Step 2: Add a Global Request Header Interceptor
To automatically attach your Token to every Retrofit request, add an interceptor to your OkHttpClient. This interceptor will fetch the Token from SharedPrefManager and inject it into the request headers before the request is sent out.
Modified RetrofitClient Code
public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl, Context context) { // Initialize SharedPrefManager using the provided Context SharedPrefManager sharedPrefManager = SharedPrefManager.getInstance(context); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // Interceptor to add Token to request headers Interceptor authInterceptor = chain -> { Request originalRequest = chain.request(); String token = sharedPrefManager.getSPToken(); Request.Builder requestBuilder = originalRequest.newBuilder(); // Add Token to header only if it's not null/empty if (token != null && !token.trim().isEmpty()) { // Adjust the header key and format to match your API's requirements // Common formats: "Authorization: Bearer {token}" or "Token: {token}" requestBuilder.header("Authorization", "Bearer " + token); } Request modifiedRequest = requestBuilder.build(); return chain.proceed(modifiedRequest); }; OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .addInterceptor(authInterceptor) // Attach the auth interceptor .build(); if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); } return retrofit; } }
Key Checks to Ensure Success
SharedPrefManager Validation: Double-check that your
getSPToken()method correctly reads the Token from SharedPreferences. For example:// Inside your SharedPrefManager class public String getSPToken() { return sharedPreferences.getString("saved_token_key", null); }Make sure you’re using the exact same key (
saved_token_keyin this example) when saving and retrieving the Token.Request Header Format: Adjust the header key and value format to match what your backend expects. If your API uses
Tokeninstead ofAuthorization, change the header line to:requestBuilder.header("Token", token);
How to Use the Updated Client
When initializing Retrofit in your Activity/Fragment, pass the Context to ensure the SharedPrefManager works correctly:
Retrofit retrofit = RetrofitClient.getClient("https://your-api-base-url.com/", this);
This setup ensures your Token is fetched properly from SharedPreferences and automatically added to every request’s headers, resolving both of your issues.
内容的提问来源于stack exchange,提问作者indriyanto Nugroho

