HTTP request in Kotlin

I am completely unfamiliar with Kotlin. I want to do a login check using the POST method and get some information using the GET method. I have a URL, username and password already from my previous project. I did not find a suitable sample project that uses this thing. Anyone please offer me any working example where I can use the GET and POST method in an HTTP request

+22
source share
9 answers

For Android, Volley is a good place to start. For all platforms, you can also check out the Ktor client.

However, you can use the standard libraries that you use in Java. For example, with HttpURLConnection you can do:

 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 easier:

 URL("https://google.com").readText() 
+17
source

Send an 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() } it.close() 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") } } } 
+6
source

Probably the easiest get

For everyone adhering to NetworkOnMainThreadException for other solutions: use AsyncTask or, even shorter, (still experimentally) Coroutines:

 launch { val jsonStr = URL("url").readText() } 

If you need to test with simple http, be sure to add to your manifest: android:usesCleartextTraffic="true"


For experimental Coroutines you need to add build.gradle as of 10/10/2018:

 kotlin { experimental { coroutines 'enable' } } dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.24.0" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.24.0" ... 
+5
source

You can use the kohttp library. This is the Kotlin DSL HTTP client. It supports the square.okhttp functions and provides them with an understandable DSL. KoHttp asynchronous calls are driven by coroutines.

httpGet extension httpGet

 val response: Response = "https://google.com/search?q=iphone".httpGet() 

You can also use asynchronous call with coroutines

 val response: Deferred<Response> = "https://google.com/search?q=iphone".asyncHttpGet() 

or DSL function for more complex queries

 val response: Response = httpGet { host = "google.com" path = "/search" param { "q" to "iphone" "safe" to "off" } } 

You can find more information in the documentation.

To get it using Gradle

 implementation 'io.github.rybalkinsd:kohttp:0.10.0' 
+3
source

Without adding additional dependencies, this works. You do not need Volley for this. This works using the current version of Kotlin as of December 2018: Kotlin 1.3.10

If you are using Android Studio, you need to add this ad to your AndroidManifest.xml:

 <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Here you must manually declare the import. The auto-import tool caused me many conflicts .:

 import android.os.AsyncTask import java.io.BufferedReader import java.io.InputStreamReader import java.io.OutputStream import java.io.OutputStreamWriter import java.net.URL import java.net.URLEncoder import javax.net.ssl.HttpsURLConnection 

You cannot perform network requests in the background thread. You must subclass AsyncTask .

To call a method:

 NetworkTask().execute(requestURL, queryString) 

Declaration:

 private class NetworkTask : AsyncTask<String, Int, Long>() { override fun doInBackground(vararg parts: String): Long? { val requestURL = parts.first() val queryString = parts.last() // Set up request val connection: HttpsURLConnection = URL(requestURL).openConnection() as HttpsURLConnection // Default is GET so you must override this for post connection.requestMethod = "POST" // To send a post body, output must be true connection.doOutput = true // Create the stream val outputStream: OutputStream = connection.outputStream // Create a writer container to pass the output over the stream val outputWriter = OutputStreamWriter(outputStream) // Add the string to the writer container outputWriter.write(queryString) // Send the data outputWriter.flush() // Create an input stream to read the response val inputStream = BufferedReader(InputStreamReader(connection.inputStream)).use { // Container for input stream data val response = StringBuffer() var inputLine = it.readLine() // Add each line to the response container while (inputLine != null) { response.append(inputLine) inputLine = it.readLine() } it.close() // TODO: Add main thread callback to parse response println(">>>> Response: $response") } connection.disconnect() return 0 } protected fun onProgressUpdate(vararg progress: Int) { } override fun onPostExecute(result: Long?) { } } 
+2
source
 import java.io.IOException import java.net.URL fun main(vararg args: String) { val response = try { URL("http://seznam.cz") .openStream() .bufferedReader() .use { it.readText() } } catch (e: IOException) { "Error with ${e.message}." } println(response) } 
+1
source

If you use Kotlin , you can make your code as concise as possible. The run method turns the receiver into this and returns the value of the block. this as HttpURLConnection creates a smart throw. bufferedReader().readText() avoids a bunch of standard code.

 return URL(url).run { openConnection().run { this as HttpURLConnection inputStream.bufferedReader().readText() } } 

You can also wrap this in an extension function.

 fun URL.getText(): String { return openConnection().run { this as HttpURLConnection inputStream.bufferedReader().readText() } } 

And call it that

 return URL(url).getText() 

Finally, if you're super lazy, you can extend the String class.

 fun String.getUrlText(): String { return URL(this).run { openConnection().run { this as HttpURLConnection inputStream.bufferedReader().readText() } } } 

And call it that

 return "http://somewhere.com".getUrlText() 
+1
source

I think using okhttp is the easiest solution. Here you can see an example for the POST method, sending json and with auth.

 val url = "https://example.com/endpoint" val client = OkHttpClient() val JSON = MediaType.get("application/json; charset=utf-8") val body = RequestBody.create(JSON, "{\"data\":\"$data\"}") val request = Request.Builder() .addHeader("Authorization", "Bearer $token") .url(url) .post(body) .build() val response = client . newCall (request).execute() println(response.request()) println(response.body()!!.string()) 

Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

UPDATE: July 7, 2019 I will give two examples using the latest versions of Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

Get method

 fun get() { val client = OkHttpClient() val url = URL("https://reqres.in/api/users?page=2") val request = Request.Builder() .url(url) .get() .build() val response = client.newCall(request).execute() val responseBody = response.body!!.string() //Response println("Response Body: " + responseBody) //we could use jackson if we got a JSON val mapperAll = ObjectMapper() val objData = mapperAll.readTree(responseBody) objData.get("data").forEachIndexed { index, jsonNode -> println("$index $jsonNode") } } 

Post method

 fun post() { val client = OkHttpClient() val url = URL("https://reqres.in/api/users") //just a string var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}" //or using jackson val mapperAll = ObjectMapper() val jacksonObj = mapperAll.createObjectNode() jacksonObj.put("name", "Rolando") jacksonObj.put("job", "Fakeador") val jacksonString = jacksonObj.toString() val mediaType = "application/json; charset=utf-8".toMediaType() val body = jacksonString.toRequestBody(mediaType) val request = Request.Builder() .url(url) .post(body) .build() val response = client.newCall(request).execute() val responseBody = response.body!!.string() //Response println("Response Body: " + responseBody) //we could use jackson if we got a JSON val objData = mapperAll.readTree(responseBody) println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".") } 
+1
source

Check out the Fuel library, an example GET request

 "https://httpbin.org/get" .httpGet() .responseString { request, response, result -> when (result) { is Result.Failure -> { val ex = result.getException() } is Result.Success -> { val data = result.get() } } } // You can also use Fuel.get("https://httpbin.org/get").responseString { ... } // You can also use FuelManager.instance.get("...").responseString { ... } 

Sample POST Request

 Fuel.post("https://httpbin.org/post") .jsonBody("{ \"foo\" : \"bar\" }") .also { println(it) } .response { result -> } 

Their documentation can be found here.

0
source

Source: https://habr.com/ru/post/1271725/


All Articles