app/app/src/main/java/com/danilafe/fencelessgrazing/requests/authenticated/AuthenticatedPostRequest.kt

42 lines
1.5 KiB
Kotlin

package com.danilafe.fencelessgrazing.requests.authenticated
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.json.JSONObject
/**
* General POST request aimed at a protected endpoint of the API. The token can be retrieved
* via a [com.danilafe.fencelessgrazing.requests.LoginRequest], or, if you've made it past the login
* screen, via Shared Preferences.
*
* @param value the value to send as JSON to the API.
* @param baseUrl the base URL of the API.
* @param apiEndpoint the API endpoint to send the request to.
* @param token the token to use to authenticate with the API.
* @param listener the listener to be called when a response is received.
* @param error the error handler to be called if a request fails.
*/
open class AuthenticatedPostRequest<T>(
private val value: T,
baseUrl: String,
apiEndpoint: String,
private val token: String,
listener: Response.Listener<String>,
error: Response.ErrorListener
) : StringRequest(Method.POST, "${baseUrl}${apiEndpoint}",
listener, error
) {
override fun getBody(): ByteArray = Gson().toJson(value).toByteArray()
override fun getBodyContentType(): String = "application/json"
override fun getHeaders(): MutableMap<String, String> {
val newMap = HashMap(super.getHeaders())
newMap["Authorization"] = "Bearer $token"
return newMap
}
}