app/app/src/main/java/com/danilafe/fencelessgrazing/requests/AuthenticatedRequest.kt

36 lines
1.4 KiB
Kotlin

package com.danilafe.fencelessgrazing.requests
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
/**
* General request aimed at a protected endpoint of the API. The token can be retrieved
* via a [LoginRequest], or, if you've made it past the login screen, via Shared Preferences.
*
* The [AuthenticatedRequest] expects to receive a string from the API endpoint; how this string
* is handled is determined by the [Response.Listener] object. One may use
* [Response.Listener.toGsonListener] to create a JSON deserializer that expects a [String].
*
* @param baseUrl the API URL base (for example, `https://dev.danilafe.com`)
* @param apiEndpoint the API endpoint to which the request is being made.
* @param token the API token used for authentication.
* @param listener the listener object called if a valid response is received.
* @param error the error listener for the request.
*/
open class AuthenticatedRequest(
baseUrl: String,
apiEndpoint: String,
private val token: String,
listener: Response.Listener<String>,
error: Response.ErrorListener
) : StringRequest(
Method.GET, "${baseUrl}${apiEndpoint}",
listener, error
) {
override fun getHeaders(): MutableMap<String, String> {
val newMap = HashMap(super.getHeaders())
newMap["Authorization"] = "Bearer $token"
return newMap
}
}