HTTP Head request using Java 11 HttpClient - Kotlin

Upasana | October 27, 2019 | 3 min read | 524 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. HTTP GET request with Java 11 HttpClient - Kotlin
  2. Using Java 11 HttpClient with Kotlin Coroutines
  3. Java 11 HttpClient with Basic Authentication
  4. Http methods for RESTful services
  5. Rest Assured API Testing Interview Questions
  6. REST Assured vs Apache HttpClient and RestTemplate
  7. 50 Java Interview Questions for SDET Automation Engineer

Recommended books for interview preparation:

Find more on this topic: