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 the preceding function is straightforward. Invoke it with appropriate values, as you would any other function:

val fullName: String = "John Wayne"
val response = post("http://example.com", "{ "full_name": $fullName")

println(response)

Easy, right? Glad you agree. Communicating with a remote server is fun with OkHttp but using Retrofit to do this is even more fun. We are almost ready to work with Retrofit, but, before we explore Retrofit, it's a good idea to properly model the data we will be sending in our HTTP requests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.142.166