Avatar ·

How to make an HTTP request in Kotlin?

Hello everyone! I need to make a simple HTTP GET request in a Kotlin (JVM) project. I'm new to the language, so I want to understand what the standard and recommended way to do this is in 2024.

I tried using the Java HttpURLConnection class, but the code turns out very cumbersome and hard to read. Here's an example of what I wrote:

import java.net.HttpURLConnection\nimport java.net.URL\n\nfun main() {\n    val url = URL("https://jsonplaceholder.typicode.com/posts/1")\n    val connection = url.openConnection() as HttpURLConnection\n    connection.requestMethod = "GET"\n    connection.connectTimeout = 5000\n    connection.readTimeout = 5000\n    val responseCode = connection.responseCode\n    println("Response Code: $responseCode")\n    va