Complete the code to create a GET request using OkHttp.
val client = OkHttpClient()
val request = Request.Builder()
.url("https://api.example.com/data")
.[1]()
.build()The get() method sets the HTTP method to GET, which is used to retrieve data.
Complete the code to create a POST request with a JSON body.
val JSON = "application/json; charset=utf-8".toMediaType() val jsonBody = "{\"name\": \"John\"}" val body = jsonBody.toRequestBody([1]) val request = Request.Builder() .url("https://api.example.com/users") .post(body) .build()
The toRequestBody() method requires the media type to specify the content type of the body. Here, JSON is the media type for JSON data.
Fix the error in the code to execute the request asynchronously.
client.newCall(request).[1](object : Callback { override fun onFailure(call: Call, e: IOException) { println("Request failed") } override fun onResponse(call: Call, response: Response) { println(response.body?.string()) } })
The enqueue() method runs the request asynchronously, calling back on success or failure.
Fill both blanks to create a GET request and print the response body safely.
val request = Request.Builder()
.url("https://api.example.com/info")
.[1]()
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
val body = response.body?.[2]()
println(body ?: "No response body")
}
override fun onFailure(call: Call, e: IOException) {}
})Use get() to set the GET method and string() to read the response body as text safely.
Fill all three blanks to create a POST request with JSON body and handle the response.
val JSON = "application/json; charset=utf-8".toMediaType() val jsonData = "{\"age\": 30}" val body = jsonData.toRequestBody([1]) val request = Request.Builder() .url("https://api.example.com/update") .[2](body) .build() client.newCall(request).enqueue(object : Callback { override fun onResponse(call: Call, response: Response) { val result = response.body?.[3]() println(result ?: "Empty response") } override fun onFailure(call: Call, e: IOException) {} })
Use JSON as media type for the body, post() to set the POST method, and string() to read the response body as text.