Junior
How to create a Retrofit?
sobes.tech AI
Answer from AI
Retrofit.Builder()
.baseUrl("https://api.example.com/") // Base URL of the API
.addConverterFactory(GsonConverterFactory.create()) // Converter for JSON parsing
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // Adapter for RxJava (optional)
// Additional settings: Interceptors, OkHttpClient
.build()
// Example API interface
interface ApiService {
@GET("users")
fun getUsers(): Call<List<User>> // Example request
}
// Using the created Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
To create an instance of Retrofit, the class Retrofit.Builder() is used. It sets the base URL, converters (such as GsonConverterFactory for JSON), and optional adapters for reactive programming (like RxJava2CallAdapterFactory). After configuring the builder, the build() method is called. Then, using the created Retrofit object, the API interface methods are looked up and instantiated using the create() method.