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()
            .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. 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