Idiomatic HTTP in Kotlin with KHTTP

What I learned today — 2 August 2018

Niel de Wet
1 min readAug 3, 2018

Performing HTTP requests in Java and by extension, Kotlin, is never simple without using a slew of libraries. The best I’ve seen is Feign, which provides nice interface-based ports (ports-and-adapters) and which integrates nicely with Spring Cloud technologies. Feign is great, but a bit heavy-handed for very simple applications.

Enter KHTTP by Kyle Clemens. KHTTP makes it simple and and straight forward to interact with resources over HTTP. What’s more, it is implemented using only native Java, with the exception of the org.json.json library.

For example, POSTing a JSON object:

import khttp.postobject LogPOSTer {@JvmStatic
fun main(args: Array<String>) {
val jsonObject = mapOf(
"timestamp" to localDateTime("2018-07-16 14:18:01"),
"level" to "DEBUG",
"logger" to "com.example.security.LoginModuleAdapter",
"thread" to "thread-0",
"message" to "[JIH] logout successful")
post("http://localhost:8080", json = jsonObject)
}
private fun localDateTime(dateTime: String): LocalDateTime = LocalDateTime.parse(dateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))}

The only concern is that the project is archived on GitHub — I hope it isn’t dead.

--

--

No responses yet