Created
April 7, 2023 07:43
-
-
Save paigeshin/ace4c159b0df1dd44c46f79720fe2a39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Retrofit API interface | |
interface MyApiService { | |
// Example API endpoint that requires an access token | |
@GET("example_endpoint") | |
suspend fun getExampleData(@Header("Authorization") authToken: String): Response<ExampleData> | |
} | |
// Retrofit API client | |
class MyApiClient(private val sharedPreferences: SharedPreferences) { | |
private val apiService = Retrofit.Builder() | |
.baseUrl("https://example.com/api/") | |
.addConverterFactory(GsonConverterFactory.create()) | |
.build() | |
.create(MyApiService::class.java) | |
suspend fun getExampleData(): ExampleData? { | |
// Get the access token from shared preferences | |
val accessToken = sharedPreferences.getString("access_token", null) | |
// Make the API request with the access token | |
val response = apiService.getExampleData("Bearer $accessToken") | |
// If the response is unauthorized (status code 401), request a new access token with the refresh token and retry the request | |
if (response.code() == 401) { | |
// Get the refresh token from shared preferences | |
val refreshToken = sharedPreferences.getString("refresh_token", null) | |
// Request a new access token with the refresh token | |
val newAccessToken = requestNewAccessToken(refreshToken) | |
// If a new access token was obtained, update it in shared preferences and retry the request | |
if (newAccessToken != null) { | |
sharedPreferences.edit().putString("access_token", newAccessToken).apply() | |
return apiService.getExampleData("Bearer $newAccessToken").body() | |
} | |
} | |
// Return the response body if the request was successful or if a new access token was obtained and the retry was successful | |
return response.body() | |
} | |
private suspend fun requestNewAccessToken(refreshToken: String): String? { | |
// Example API endpoint for requesting a new access token with a refresh token | |
val response = apiService.refreshAccessToken(refreshToken) | |
return if (response.isSuccessful) response.body()?.accessToken else null | |
} | |
} | |
// Example usage | |
val myApiClient = MyApiClient(sharedPreferences) | |
val exampleData = myApiClient.getExampleData() | |
if (exampleData != null) { | |
// Process example data | |
} else { | |
// Handle error | |
} | |
This code assumes that you have implemented an API endpoint for requesting a new access token with a refresh token, and that the response contains both the new access token and the refresh token. You may need to modify the code to fit your specific implementation. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment