I want to do a login validation using POST method and to get some information using GET method.
I've URL, server Username and Password already of my previous project.
Ktor is multiplatform, yes multiplatform! It means that we can deploy Ktor applications anywhere, and not only as a server, but we can also consume microservices on Android, iOS, or JS with Ktor Client.
The Kotlin client relies on the kotlinx serialization library.
For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.
However, you can also use standard Java libraries like java.net.HttpURLConnection
which is part of the Java SDK:
fun sendGet() { val url = URL("http://www.google.com/") with(url.openConnection() as HttpURLConnection) { requestMethod = "GET" // optional default is GET println("\nSent 'GET' request to URL : $url; Response Code : $responseCode") inputStream.bufferedReader().use { it.lines().forEach { line -> println(line) } } } }
Or simpler:
URL("https://google.com").readText()
Send HTTP POST/GET request with parameters using HttpURLConnection
:
POST with Parameters:
fun sendPostRequest(userName:String, password:String) { var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8") reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") val mURL = URL("<Your API Link>") with(mURL.openConnection() as HttpURLConnection) { // optional default is GET requestMethod = "POST" val wr = OutputStreamWriter(getOutputStream()); wr.write(reqParam); wr.flush(); println("URL : $url") println("Response Code : $responseCode") BufferedReader(InputStreamReader(inputStream)).use { val response = StringBuffer() var inputLine = it.readLine() while (inputLine != null) { response.append(inputLine) inputLine = it.readLine() } println("Response : $response") } } }
GET with Parameters:
fun sendGetRequest(userName:String, password:String) { var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8") reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") val mURL = URL("<Yout API Link>?"+reqParam) with(mURL.openConnection() as HttpURLConnection) { // optional default is GET requestMethod = "GET" println("URL : $url") println("Response Code : $responseCode") BufferedReader(InputStreamReader(inputStream)).use { val response = StringBuffer() var inputLine = it.readLine() while (inputLine != null) { response.append(inputLine) inputLine = it.readLine() } it.close() println("Response : $response") } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With