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()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(15))
            .followRedirects(HttpClient.Redirect.NORMAL)
            .build()

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

    val request = HttpRequest.newBuilder()
            .POST(ofFormData(data)) (2)
            .uri(URI.create("http://example.com"))
            .setHeader("User-Agent", "Espion Bot")
            .header("Content-Type", "application/x-www-form-urlencoded")    (1)
            .build()

    val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
    // print status code & body
    println(response.statusCode())
    println(response.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()) {
            result.append("&")
        }
        val encodedName = URLEncoder.encode(key.toString(), StandardCharsets.UTF_8)
        val encodedValue = URLEncoder.encode(value.toString(), StandardCharsets.UTF_8)
        result.append(encodedName)
        if (encodedValue != null) { (1)
            result.append("=")
            result.append(encodedValue)
        }
    }
    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: