I have a kotlin script that gets a token from a server. It then uses that token to perform another request. But, I can't seem to use the token in the next request because the token has a local scope.
This is my code:
class requests{
private val client = OkHttpClient()
private val coroutineScope = CoroutineScope(Dispatchers.Default)
fun run() {
coroutineScope.launch {
val postBody = "encodedinfo".trimMargin()
val request = Request.Builder()
.url("https://example.com")
.post(postBody.toRequestBody(MEDIA_TYPE_MARKDOWN))
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
val token = response.body!!.string()
}
}
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
}
With this code I can't use the token variable outside of the request code block. This block of code:
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
val token = response.body!!.string()
}
This is the first request that gets the token variable and I need the token so that I can use it in another function so that I can perform the second request and load the users info.