Bird
Raised Fist0
Android Kotlinmobile~5 mins

GET and POST requests in Android Kotlin

Choose your learning style10 modes available
Introduction

GET and POST requests let your app talk to the internet. GET asks for data, POST sends data.

When your app needs to get information from a website or server.
When your app needs to send user input or data to a server.
When you want to load a list of items from the internet.
When you want to submit a form or save data online.
When your app communicates with online services or APIs.
Syntax
Android Kotlin
val url = URL("https://example.com/api")

// GET request
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"

// POST request
val connectionPost = url.openConnection() as HttpURLConnection
connectionPost.requestMethod = "POST"
connectionPost.doOutput = true
val outputStream = connectionPost.outputStream
outputStream.write(postData.toByteArray())
outputStream.flush()

Use GET to request data from a server.

Use POST to send data to a server, like form info.

Examples
This example shows a simple GET request to get data from a server.
Android Kotlin
val url = URL("https://api.example.com/data")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
val response = connection.inputStream.bufferedReader().readText()
This example sends data using POST to the server, like submitting a form.
Android Kotlin
val url = URL("https://api.example.com/submit")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.doOutput = true
val postData = "name=John&age=30"
connection.outputStream.use { it.write(postData.toByteArray()) }
val response = connection.inputStream.bufferedReader().readText()
Sample App

This app makes a GET request to get a post and a POST request to send data. It prints the server responses in the console.

Android Kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(android.R.layout.simple_list_item_1)

        CoroutineScope(Dispatchers.IO).launch {
            val getResponse = makeGetRequest("https://jsonplaceholder.typicode.com/posts/1")
            val postResponse = makePostRequest("https://jsonplaceholder.typicode.com/posts", "title=Hello&body=World")

            println("GET response: $getResponse")
            println("POST response: $postResponse")
        }
    }

    private fun makeGetRequest(urlString: String): String {
        val url = URL(urlString)
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        return connection.inputStream.bufferedReader().readText()
    }

    private fun makePostRequest(urlString: String, postData: String): String {
        val url = URL(urlString)
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.doOutput = true
        connection.outputStream.use { it.write(postData.toByteArray()) }
        return connection.inputStream.bufferedReader().readText()
    }
}
OutputSuccess
Important Notes

Network calls must run off the main thread to avoid freezing the app.

Use libraries like Retrofit or Ktor for easier network requests in real apps.

Always check for errors and handle exceptions when making requests.

Summary

GET requests fetch data from a server.

POST requests send data to a server.

Network calls should run in background threads to keep the app smooth.

Practice

(1/5)
1. What is the main purpose of a GET request in Android Kotlin networking?
easy
A. To fetch data from a server
B. To send data to a server
C. To update the UI thread
D. To store data locally

Solution

  1. Step 1: Understand GET request purpose

    A GET request is used to retrieve or fetch data from a server without changing any data on the server.
  2. Step 2: Compare with other request types

    POST requests send data to the server, unlike GET which only fetches data.
  3. Final Answer:

    To fetch data from a server -> Option A
  4. Quick Check:

    GET = fetch data [OK]
Hint: GET fetches data; POST sends data [OK]
Common Mistakes:
  • Confusing GET with POST request purpose
  • Thinking GET modifies server data
  • Mixing UI updates with network requests
2. Which of the following is the correct way to start a POST request using Kotlin's HttpURLConnection?
easy
A. connection.requestMethod = "GET"
B. connection.requestMethod = "POST"
C. connection.method = "POST"
D. connection.setRequestMethod("GET")

Solution

  1. Step 1: Identify correct property for request method

    In Kotlin, HttpURLConnection uses requestMethod property to set the HTTP method.
  2. Step 2: Confirm correct method value for POST

    To make a POST request, set requestMethod to "POST" exactly.
  3. Final Answer:

    connection.requestMethod = "POST" -> Option B
  4. Quick Check:

    POST method set by requestMethod = "POST" [OK]
Hint: Use requestMethod property with "POST" string [OK]
Common Mistakes:
  • Using wrong property name like method
  • Setting GET instead of POST
  • Using Java-style setRequestMethod() in Kotlin
3. What will be the output of this Kotlin code snippet when making a GET request?
val url = URL("https://example.com/data")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
val responseCode = connection.responseCode
println(responseCode)
medium
A. 500
B. 404
C. 200
D. Compilation error

Solution

  1. Step 1: Understand the code flow

    The code opens a connection to the URL and sets the method to GET, then reads the response code from the server.
  2. Step 2: Predict typical HTTP response code

    Assuming the URL is valid and reachable, a successful GET request returns HTTP status code 200.
  3. Final Answer:

    200 -> Option C
  4. Quick Check:

    Successful GET returns 200 [OK]
Hint: 200 means OK response from server [OK]
Common Mistakes:
  • Assuming responseCode is a string
  • Confusing 404 (not found) with success
  • Thinking code will not compile
4. Identify the error in this Kotlin code snippet for sending a POST request:
val url = URL("https://example.com/api")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
val outputStream = connection.outputStream
outputStream.write("data=hello".toByteArray())
outputStream.flush()
outputStream.close()
medium
A. Missing setting connection.doOutput = true
B. Using write() instead of writeBytes()
C. Incorrect requestMethod value
D. Not reading the response code

Solution

  1. Step 1: Check POST request setup

    For POST requests, doOutput must be set to true to send data in the request body.
  2. Step 2: Identify missing property

    The code does not set connection.doOutput = true, so writing to outputStream will fail or not send data.
  3. Final Answer:

    Missing setting connection.doOutput = true -> Option A
  4. Quick Check:

    doOutput = true needed for POST body [OK]
Hint: Set doOutput true before writing POST data [OK]
Common Mistakes:
  • Forgetting doOutput = true for POST
  • Confusing write() method usage
  • Ignoring response reading after POST
5. You want to send JSON data in a POST request using Kotlin. Which sequence correctly sets up the connection and sends the JSON string {"name":"John"}?
hard
A. Set requestMethod to "GET", write JSON bytes to outputStream, set doOutput = true
B. Set requestMethod to "POST", set doOutput = false, write JSON string directly to connection
C. Set requestMethod to "POST", write JSON bytes to outputStream without setting doOutput, set Content-Type header to "text/plain"
D. Set requestMethod to "POST", set doOutput = true, set Content-Type header to "application/json", write JSON bytes to outputStream

Solution

  1. Step 1: Correct HTTP method and output setup

    For sending data, requestMethod must be "POST" and doOutput must be true to allow writing data.
  2. Step 2: Set proper headers and write data

    Content-Type header should be "application/json" to indicate JSON data. Then write JSON bytes to outputStream.
  3. Final Answer:

    Set requestMethod to "POST", set doOutput = true, set Content-Type header to "application/json", write JSON bytes to outputStream -> Option D
  4. Quick Check:

    POST + doOutput + JSON header + write bytes [OK]
Hint: POST JSON needs doOutput true and JSON content-type [OK]
Common Mistakes:
  • Using GET method to send data
  • Not setting Content-Type header correctly
  • Forgetting doOutput = true
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard