Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Introducing Retrofit Call

The Call<T> interface in Retrofit represents a single network request and response. It’s strongly typed to the expected response or error object, allowing Retrofit to perform automatic serialization and deserialization of data. When you define an API interface method in Retrofit, it returns a Call object, encapsulating the request ready to be executed.

@GET("user")
fun getProfile(): Call<User>

Reading the ResponseBody

You handle raw responses from the server using Retrofit’s ResponseBody. Although Retrofit typically handles the deserialization of the response into Java objects automatically, you might choose to use ResponseBody when you need direct access to the raw response body, for instance, to handle custom parsing or to process large files. Custom parsing is what you’ll do in this lesson.

@GET("user")
fun getProfile(): Call<ResponseBody>

Closing the ReponseBody

Maintaining an active connection to the web server is essential for supporting each ResponseBody. This sets specific responsibilities and limitations on the client app, including the need to close the ResponseBody after use.

Sending a RequestBody

A RequestBody in Retrofit represents the body of an HTTP request. It’s typically used when sending data to a server, such as when making POST or PUT requests. Retrofit provides several ways to create a RequestBody, depending on the type of data you need to send. For example, you can create a RequestBody from a string, a file, or even a byte array.

val body = RequestBody.create(MediaType.parse("application/json"), jsonBody)
@POST("user/register")
fun registerUser(@Body body: RequestBody): Call<ResponseBody>

Making Synchronous vs. Asynchronous Requests

execute(): This method executes the request synchronously on the current thread, blocking the thread until the response is received or an error occurs. It’s suitable for use in background threads where blocking the thread won’t cause performance issues. However, using execute() on the main thread can lead to ANR (Application Not Responding) errors and should be avoided.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo