fun httpGetRequestSync() {
val httpClient: HttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build()
val requestHead = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.example.com"))
.build()
val httpResponse = httpClient.send(requestHead, BodyHandlers.ofString())
println("httpResponse statusCode = ${httpResponse.statusCode()}")
println(httpResponse.body())
}
HTTP GET request with Java 11 HttpClient - Kotlin
Upasana | October 27, 2019 | 2 min read | 827 views | java-httpclient
In this article we will learn how to make HTTP GET request using Java 11 HttpClient Api in sync as well as async fully non-blocking mode.
Java 11 provides HttpClient API that supports fully non-blocking IO for making network HTTP requests.
Making HTTP GET request in sync mode
Making HTTP GET request in Async mode
fun httpGetRequestAsync() {
val httpClient: HttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build()
val requestHead = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.example.com"))
.build()
httpClient
.sendAsync(requestHead, BodyHandlers.ofString())
.thenApply(HttpResponse<String>::body)
.thenAccept { htmlBody -> println(htmlBody) }
.join()
}
Kotlin coroutines can be used with HttpClient for making network requests without blocking on threads. We need to add the below Kotlin JDK integration library to make code work.
build.gradle
dependencies {
compile('org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2')
compile('org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.2')
}
Using await()
extension on CompletionStage
suspends the current coroutine until the response becomes available. Thus callback based code is converted to more readable sequential code.
HTTP GET using Kotlin Coroutine
suspend fun httpGetRequestCoroutine() {
val httpClient: HttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build()
val requestHead = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.example.com"))
.build()
val httpResponse = httpClient.sendAsync(requestHead, BodyHandlers.ofString()).await()
println(httpResponse.body())
}
fun makeHttpGetRequestCoroutine() {
runBlocking {
httpGetRequestCoroutine()
}
}
That’s all for now.
Top articles in this category:
- HTTP Head request using Java 11 HttpClient - Kotlin
- Java 11 HttpClient with Basic Authentication
- Using Java 11 HttpClient with Kotlin Coroutines
- Http methods for RESTful services
- Rest Assured API Testing Interview Questions
- REST Assured vs Apache HttpClient and RestTemplate
- 50 Java Interview Questions for SDET Automation Engineer
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..