Sending requests to a server with OkHttp

As previously stated, OkHttp's APIs were built with ease of use in mind. As a consequence, sending requests via OkHttp is quick and hassle-free. The following is a post(String, String) method that takes a URL and JSON request body as its arguments and sends a POST request to the specified URL with the JSON body:

fun post(url: String, json: String): String {  val mediaType: MediaType = MediaType.parse("application/json;                                              charset=utf-8")  val client:OkHttpClient = OkHttpClient()  val body: RequestBody = RequestBody.create(mediaType, json)  val request: Request = Request.Builder()                                .url(url)                                .post(body)                                .build()  val response: Response = client.newCall(request).execute()  return response.body().string()}

Using ...

Get Kotlin Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.