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.