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() + ".") }
source share