Sling Academy
Home/Kotlin/How to Use the `HttpURLConnection` Class in Kotlin

How to Use the `HttpURLConnection` Class in Kotlin

Last updated: November 30, 2024

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.

Next Article: Making GET Requests with Kotlin

Previous Article: Introduction to Networking in Kotlin

Series: Networking in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin