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.
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()
}
}