What are the main components and objects used when working with Retrofit in your project?
sobes.tech AI
Answer from AI
When working with Retrofit in an Android project, the main components and objects are as follows:
-
Retrofit.Builder — used to create an instance of Retrofit, where the base URL, converters (e.g., GsonConverterFactory), and other settings are specified.
-
API Interface — describes HTTP requests using annotations (@GET, @POST, etc.) and methods that return Call<T> or other types.
-
Call<T> — an object representing an HTTP request that can be executed synchronously or asynchronously.
-
Converter Factory — responsible for converting data from JSON (or other formats) into Java/Kotlin objects and vice versa.
-
OkHttpClient — an HTTP client that can be configured and passed to Retrofit to manage network requests.
Example of creating Retrofit and an API interface:
interface ApiService {
@GET("users/{id}")
fun getUser(@Path("id") userId: String): Call<User>
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
// Usage
apiService.getUser("123").enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
// handle response
}
override fun onFailure(call: Call<User>, t: Throwable) {
// handle error
}
})
Thus, Retrofit simplifies working with REST APIs by providing a convenient and type-safe way to perform network requests.