Android开发:如何存储登录Token并在OkHttp拦截器中使用
Hey there! As an Android dev newbie, this is a super common (and important) step—let’s walk through it clearly. We’ll cover storing the token securely and automatically adding it to every request via an OkHttp interceptor.
1. Pick a Storage Method
For auth tokens, the go-to lightweight, persistent option is SharedPreferences. It’s easy to implement and perfect for small pieces of data like tokens. If you’re dealing with extra-sensitive data later, you can switch to EncryptedSharedPreferences, but let’s start with the basics.
2. Build a Session Manager for Token Handling
Make a helper class to handle saving, retrieving, and clearing the token. This keeps your code clean and reusable:
package com.example.dell01.firstapplication; import android.content.Context; import android.content.SharedPreferences; public class SessionManager { private static final String PREF_NAME = "UserSession"; private static final String KEY_TOKEN = "auth_token"; private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; public SessionManager(Context context) { sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); editor = sharedPreferences.edit(); } // Save token after successful login public void saveAuthToken(String token) { editor.putString(KEY_TOKEN, token); editor.apply(); } // Retrieve saved token public String getAuthToken() { return sharedPreferences.getString(KEY_TOKEN, null); } // Clear token (for logout) public void clearSession() { editor.clear(); editor.apply(); } }
3. Update OkHttp Interceptor to Use Stored Token
Your current interceptor uses a hardcoded token—let’s modify it to pull the token from our SessionManager instead. We’ll only add the header if a token exists (so login requests don’t get blocked):
OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); SessionManager sessionManager = new SessionManager(YourApp.getContext()); // Replace with your app's context String token = sessionManager.getAuthToken(); Request.Builder builder = originalRequest.newBuilder(); // Add Token header only if token exists if (token != null) { builder.header("Token", token); } return chain.proceed(builder.build()); } }) .build();
Pro tip: Create a custom Application class to provide a static context (don’t use an Activity context here—it can cause memory leaks!)
4. Fix Your APIClient Class
Right now, your okHttpClient instance isn’t being used in the Retrofit builder. Let’s fix that and ensure the Retrofit singleton uses our configured OkHttpClient:
package com.example.dell01.firstapplication.service; import com.example.dell01.firstapplication.SessionManager; import com.example.dell01.firstapplication.YourApp; // Add your custom Application class import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class APIClient { public static final String BASE_URL = "actual url"; private static Retrofit retrofit = null; // Create OkHttpClient with our token interceptor private static OkHttpClient getOkHttpClient() { return new OkHttpClient().newBuilder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); SessionManager sessionManager = new SessionManager(YourApp.getContext()); String token = sessionManager.getAuthToken(); Request.Builder builder = originalRequest.newBuilder(); if (token != null) { builder.header("Token", token); } return chain.proceed(builder.build()); } }) .build(); } public static Retrofit getAPIClient(){ if(retrofit == null){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(getOkHttpClient()) // Don't forget this critical line! .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
5. Save the Token After Successful Login
When your login API call returns a token, use the SessionManager to save it immediately:
// Example login call in your Activity/Fragment APIInterface apiInterface = APIClient.getAPIClient().create(APIInterface.class); Call<Token> call = apiInterface.getToken("your_username", "your_password"); call.enqueue(new Callback<Token>() { @Override public void onResponse(Call<Token> call, Response<Token> response) { if (response.isSuccessful() && response.body() != null) { String authToken = response.body().getToken(); // Adjust to match your Token model's field name SessionManager sessionManager = new SessionManager(YourActivity.this); sessionManager.saveAuthToken(authToken); // Navigate to home screen or handle post-login tasks } } @Override public void onFailure(Call<Token> call, Throwable t) { // Handle login failure (show error message, etc.) } });
Quick Reminders
- Always use
apply()instead ofcommit()for SharedPreferences edits—it’s asynchronous and avoids blocking the main thread. - If your Token model uses a different field name (like
access_token), adjustresponse.body().getToken()to match. - For logout, just call
sessionManager.clearSession()to remove the token.
内容的提问来源于stack exchange,提问作者Kumar

