Submit Form with Java 11 HttpClient - Kotlin

Upasana | June 10, 2020 | 2 min read | 0 views

In this article we will show how to submit a URL encoded form using Java 11 HttpClient Api in sync as well as async fully non-blocking mode using Kotlin.

Java HttpClient does not have built-in support to send a POST request with x-www-form-urlencoded, but we can easily add this feature using few lines of code.

Java 11 HttpClient

We will create a simple httpClient with some default configuration and use this client to make a POST request.

HttpClient Post request
fun main() {
    val httpClient = HttpClient.newBuilder()

    // form parameters
    val data: MutableMap<Any, Any> = HashMap()
    data["username"] = "<username>"
    data["password"] = "<password>"

    val request = HttpRequest.newBuilder()
            .POST(ofFormData(data)) (2)
            .setHeader("User-Agent", "Espion Bot")
            .header("Content-Type", "application/x-www-form-urlencoded")    (1)

    val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
    // print status code & body
1 Setting Content-Type to application/x-www-form-urlencoded is crucial here
2 Utility method that converts form params to x-www-form-urlencoded String

Formdata (x-www-form-urlencoded)

We will create a simple utility method that takes a Map of key/value pair and converts it to a String that is sable for use as an application/x-www-form-urlencoded

Utility method to convert Map to x-www-form-urlencoded String
fun ofFormData(data: Map<Any, Any>): HttpRequest.BodyPublisher? {
    val result = StringBuilder()
    for ((key, value) in data) {
        if (result.isNotEmpty()) {
        val encodedName = URLEncoder.encode(key.toString(), StandardCharsets.UTF_8)
        val encodedValue = URLEncoder.encode(value.toString(), StandardCharsets.UTF_8)
        if (encodedValue != null) { (1)
    return HttpRequest.BodyPublishers.ofString(result.toString())
1 Do not append = along with value if value is null

Top articles in this category:
  1. Allow insecure SSL in Java 11 HttpClient
  2. Difference between ExecutorService submit and execute method
  3. Is Java Pure Object Oriented Language?
  4. ThreadLocal with examples in Java
  5. Precision and scale for a Double in java
  6. Difference between Implementing Runnable and Extending Thread
  7. What is polymorphism in Java OOP

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.