When developing Android or Kotlin-based desktop applications, interacting with web services often requires sending HTTP requests. The HttpURLConnection class is a common way to handle these HTTP operations in Kotlin. In this article, we will cover how to utilize HttpURLConnection to send GET and POST requests.

Setting Up a GET Request

To send an HTTP GET request, we'll use HttpURLConnection to connect to a specified URL and retrieve the resource at that location.

import java.net.HttpURLConnection
import java.net.URL

fun sendGetRequest(url: String) {
    val obj = URL(url)
    with(obj.openConnection() as HttpURLConnection) {
        // Set request method
        requestMethod = "GET"

        // Print response code
        println("Response Code: $responseCode")
        
        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

fun main() {
    sendGetRequest("https://api.example.com/data")
}

Here's a breakdown of the code:

  • First, we import the necessary classes.
  • We create a URL object and open a connection using openConnection().
  • We set the request method to GET and read the response using an InputStream.
  • The response is printed line by line to the console.

Setting Up a POST Request

Sending data to a server typically requires an HTTP POST request. Here's an example of how you can send data using HttpURLConnection.

import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL

fun sendPostRequest(url: String, jsonData: String) {
    val obj = URL(url)
    with(obj.openConnection() as HttpURLConnection) {
        // Enable input and output
        doOutput = true
        requestMethod = "POST"
        setRequestProperty("Content-Type", "application/json; utf-8")
        
        // Write the request body
        outputStream.use { os ->
            val input = jsonData.toByteArray(charset("utf-8"))
            os.write(input, 0, input.size)
        }

        // Print response code
        println("Response Code: $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

fun main() {
    val json = "{ \"name\": \"sample\", \"message\": \"hello\" }"
    sendPostRequest("https://api.example.com/create", json)
}

Explanation of the POST request:

  • doOutput = true is necessary so that you can write data to the connection via OutputStream.
  • Set the "Content-Type" header to let the server know you're sending JSON data.
  • Use the OutputStream to write the JSON payload into the request.
  • The response from the server is then read similarly to the GET request.

By following these examples, you can integrate HTTP interactions into your Kotlin applications effectively using HttpURLConnection. Always remember to handle exceptions and edge cases, such as network timeouts, to create a robust networked application.