Bird
Raised Fist0
Android Kotlinmobile~20 mins

GET and POST requests in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: NetworkRequestScreen
This screen lets the user send GET and POST requests to a test API and shows the response.
Target UI
┌───────────────────────────────┐
│ Network Requests              │
├───────────────────────────────┤
│ [GET Data]                   │
│ Response:                    │
│ <empty area>                 │
│                               │
│ [POST Data]                  │
│ Enter message: [__________]  │
│ [Send POST]                  │
└───────────────────────────────┘
Add a button labeled 'GET Data' that fetches data from https://jsonplaceholder.typicode.com/posts/1 using a GET request.
Display the fetched JSON response text below the GET button.
Add a TextField for user input labeled 'Enter message'.
Add a button labeled 'Send POST' that sends the entered message as JSON to https://jsonplaceholder.typicode.com/posts using a POST request.
Display the server response from the POST request below the POST button.
Show loading indicators while requests are in progress.
Handle errors by showing a simple error message in the response area.
Starter Code
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

class NetworkRequestScreen : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      // TODO: Add UI and network request code here
    }
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection

class NetworkRequestScreen : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      NetworkRequestContent()
    }
  }
}

@Composable
fun NetworkRequestContent() {
  var getResponse by remember { mutableStateOf("") }
  var postResponse by remember { mutableStateOf("") }
  var postMessage by remember { mutableStateOf("") }
  var isLoadingGet by remember { mutableStateOf(false) }
  var isLoadingPost by remember { mutableStateOf(false) }

  val coroutineScope = rememberCoroutineScope()

  Column(modifier = Modifier.padding(16.dp)) {
    Button(onClick = {
      isLoadingGet = true
      getResponse = ""
      coroutineScope.launch(Dispatchers.IO) {
        try {
          val url = URL("https://jsonplaceholder.typicode.com/posts/1")
          val connection = url.openConnection() as HttpURLConnection
          connection.requestMethod = "GET"
          connection.connectTimeout = 5000
          connection.readTimeout = 5000

          val responseCode = connection.responseCode
          if (responseCode == HttpsURLConnection.HTTP_OK) {
            val reader = BufferedReader(InputStreamReader(connection.inputStream))
            val response = reader.readText()
            reader.close()
            isLoadingGet = false
            getResponse = response
          } else {
            isLoadingGet = false
            getResponse = "Error: Response code $responseCode"
          }
          connection.disconnect()
        } catch (e: Exception) {
          isLoadingGet = false
          getResponse = "Error: ${e.message}"
        }
      }
    }) {
      Text("GET Data")
    }

    Spacer(modifier = Modifier.height(8.dp))

    if (isLoadingGet) {
      Text("Loading GET data...", style = MaterialTheme.typography.bodyMedium)
    } else {
      Text(getResponse, style = MaterialTheme.typography.bodyMedium)
    }

    Spacer(modifier = Modifier.height(24.dp))

    OutlinedTextField(
      value = postMessage,
      onValueChange = { postMessage = it },
      label = { Text("Enter message") },
      modifier = Modifier.fillMaxWidth()
    )

    Spacer(modifier = Modifier.height(8.dp))

    Button(onClick = {
      if (postMessage.isBlank()) {
        postResponse = "Please enter a message to send."
        return@Button
      }
      isLoadingPost = true
      postResponse = ""
      coroutineScope.launch(Dispatchers.IO) {
        try {
          val url = URL("https://jsonplaceholder.typicode.com/posts")
          val connection = url.openConnection() as HttpURLConnection
          connection.requestMethod = "POST"
          connection.setRequestProperty("Content-Type", "application/json; utf-8")
          connection.doOutput = true
          connection.connectTimeout = 5000
          connection.readTimeout = 5000

          val jsonInputString = "{\"title\": \"$postMessage\", \"body\": \"$postMessage\", \"userId\": 1}"

          connection.outputStream.use { os ->
            val input = jsonInputString.toByteArray(Charsets.UTF_8)
            os.write(input, 0, input.size)
          }

          val responseCode = connection.responseCode
          if (responseCode == HttpsURLConnection.HTTP_CREATED || responseCode == HttpsURLConnection.HTTP_OK) {
            val reader = BufferedReader(InputStreamReader(connection.inputStream))
            val response = reader.readText()
            reader.close()
            isLoadingPost = false
            postResponse = response
          } else {
            isLoadingPost = false
            postResponse = "Error: Response code $responseCode"
          }
          connection.disconnect()
        } catch (e: Exception) {
          isLoadingPost = false
          postResponse = "Error: ${e.message}"
        }
      }
    }) {
      Text("Send POST")
    }

    Spacer(modifier = Modifier.height(8.dp))

    if (isLoadingPost) {
      Text("Sending POST data...", style = MaterialTheme.typography.bodyMedium)
    } else {
      Text(postResponse, style = MaterialTheme.typography.bodyMedium)
    }
  }
}

This solution uses Jetpack Compose to build the UI with two buttons and a text field. It uses Kotlin coroutines to perform network requests off the main thread.

When the user taps 'GET Data', it sends a GET request to the test API and shows the JSON response or an error message.

When the user enters text and taps 'Send POST', it sends a POST request with JSON containing the message. The response or error is shown below.

Loading states show simple text indicators while waiting for network responses.

HttpURLConnection is used for simplicity and compatibility. The UI updates reactively with Compose state variables.

Final Result
Completed Screen
┌───────────────────────────────┐
│ Network Requests              │
├───────────────────────────────┤
│ [GET Data]                   │
│ Response:                    │
│ {                           │
│   "userId": 1,             │
│   "id": 1,                 │
│   "title": "...",         │
│   "body": "..."           │
│ }                           │
│                               │
│ [POST Data]                  │
│ Enter message: [Hello API!]  │
│ [Send POST]                  │
│ Response:                   │
│ {                           │
│   "id": 101,               │
│   "title": "Hello API!", │
│   "body": "Hello API!",  │
│   "userId": 1              │
│ }                           │
└───────────────────────────────┘
Tap 'GET Data' button triggers a GET request and shows JSON response below.
Enter text in the input field and tap 'Send POST' to send POST request and show response.
Loading text appears while waiting for network responses.
Error messages appear if network fails.
Stretch Goal
Add a pull-to-refresh gesture to reload the GET data.
💡 Hint
Use SwipeRefresh from accompanist library or Compose's built-in pull refresh to trigger the GET request again.

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