HTTP Head request using Java 11 HttpClient - Kotlin

Carvia Tech | October 27, 2019 | 3 min read | 2 views | java-httpclient


In this article we will learn how to make HTTP Head request using Java 11 HttpClient Api. HttpClient supports both sync and async versions for send request method.
We will use Kotlin in this article.
Http HEAD vs GET

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

HttpClient does not provide predefined methods for making HTTP HEAD calls, but we can always use method api to make HEAD request.

Making the HTTP HEAD request

Make HTTP Head Request - Sync method
fun httpHeadRequestSync() {
    val httpClient: HttpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build()
    val requestHead = HttpRequest.newBuilder()
            .method("HEAD", HttpRequest.BodyPublishers.noBody())    (1)
            .uri(URI.create("https://www.example.com"))
            .build()
    val httpResponse = httpClient.send(requestHead, BodyHandlers.discarding())  (2)
    println("httpResponse statusCode = ${httpResponse.statusCode()}")
    println(httpResponse.headers().toString())
}
1 For HTTP HEAD, body is not required, so are using noBody() method
2 We can safely discard the body part for HTTP HEAD responses.

In a very similar fashion, we can write asynchronous version of the same request.

Make HTTP Head Request - Async method
fun httpHeadRequestAsync() {
    val httpClient: HttpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build()
    val requestHead = HttpRequest.newBuilder()
            .method("HEAD", HttpRequest.BodyPublishers.noBody())
            .uri(URI.create("https://www.example.com"))
            .build()
    httpClient.sendAsync(requestHead, BodyHandlers.discarding())
            .whenComplete { t, u ->
                println("httpResponse statusCode = ${t.statusCode()}")
                println(t.headers().toString())
            }
            .join()
}

Using Kotlin Coroutines

We can leverage Kotlin Coroutines with Java 11 HttpClient which replaces chaining of callbacks with sequential code. This increases readability of the program, and also reduces burden of threads to some extent. The best part is that Java 11 HttpClient has support for performing completely asynchronous requests using non-blocking IO.

HttpClient returns CompletableFuture when we invoke sendAsync() api instead of raw HttpResponse. We can use CompletionStage.await() kotlin extension defined in kotlinx-coroutines-jdk8 library to suspend the current coroutine until the response becomes available.

We need to add the below dependency to the build.gradle to make Kotlin coroutines work.

build.gradle
dependencies {
    compile('org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2')
    // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-jdk8
    compile('org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.2')
}
HTTP HEAD request with Kotlin Coroutines
suspend fun httpHeadRequestCoroutine() {
    val httpClient: HttpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(20))
            .build()
    val requestHead = HttpRequest.newBuilder()
            .method("HEAD", HttpRequest.BodyPublishers.noBody())
            .uri(URI.create("https://www.example.com"))
            .build()
    val httpResponse = httpClient.sendAsync(requestHead, BodyHandlers.discarding()).await() (1)
    println("httpResponse statusCode = ${httpResponse.statusCode()}")
    println(httpResponse.headers().toString())
}

fun makeHttpHeadRequestCoroutine() {
    runBlocking {
        httpHeadRequestCoroutine()
    }
}
1 await() method Awaits for completion of the completion stage without blocking a thread. This method is provided by org.jetbrains.kotlinx:kotlinx-coroutines-jdk8

That’s all for now.


Top articles in this category:
  1. SDET: Rest Assured Interview Questions
  2. Top 50 SDET Java Programming Interview Questions & Answers
  3. SDET: JUnit interview questions for automation engineer
  4. Java 11 HttpClient with Basic Authentication
  5. HTTP GET request with Java 11 HttpClient - Kotlin
  6. Using Java 11 HttpClient with Kotlin Coroutines
  7. Commonly used Http methods in RESTful services



Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info