Created
March 26, 2023 17:23
-
-
Save ismailbenhallam/4ce537954a2e1dd22bee806c8c1409de 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
package coroutines | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.coroutineScope | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.runBlocking | |
import java.net.URI | |
import java.net.http.HttpClient | |
import java.net.http.HttpRequest | |
import java.net.http.HttpResponse | |
import java.net.http.HttpResponse.BodyHandler | |
import kotlin.coroutines.resume | |
import kotlin.coroutines.resumeWithException | |
import kotlin.coroutines.suspendCoroutine | |
private suspend fun main() = runBlocking { | |
val client = HttpClient.newHttpClient() | |
val request = HttpRequest.newBuilder(URI("https://example.com/")).GET().build() | |
launch { sendRequestAndPrintResultSuspendable(client, request) } | |
println(">> We don't have to wait for the response..") | |
} | |
suspend fun sendRequestAndPrintResultSuspendable(client: HttpClient, request: HttpRequest) = | |
coroutineScope { | |
launch(Dispatchers.IO) { | |
val response = client.sendSuspendable(request, HttpResponse.BodyHandlers.ofString()) | |
response.run { | |
println("from ${Thread.currentThread().name}") | |
println("Status code: ${statusCode()}"); | |
println("Headers: ${headers().allValues("content-type")}"); | |
println("Body: ${body().take(15)}..."); | |
} | |
} | |
} | |
@OptIn(ExperimentalCoroutinesApi::class) | |
private suspend fun <T> HttpClient.sendSuspendable(request: HttpRequest, bodyHandler: BodyHandler<T>): HttpResponse<T> { | |
return suspendCoroutine { continuation -> | |
sendAsync(request, bodyHandler).whenComplete { response, exception -> | |
if (exception == null) { | |
continuation.resume(response) | |
} else { | |
continuation.resumeWithException(exception) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment