Submit Form with Java 11 HttpClient - Kotlin

Carvia Tech | 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. What is difference between ExecutorService submit and execute method
  3. Is Java Pure Object Oriented Language?
  4. What do you understand by Java Memory Model?
  5. What is volatile keyword in Java
  6. Comparable vs Comparator in Java
  7. Troubleshooting Deadlock in Java

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

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