Junior — Middle
How to implement sending a network request using the Retrofit library?
sobes.tech AI
Answer from AI
To send a network request using Retrofit, you need to follow several steps:
- Add the Retrofit dependency to your project.
- Create an interface describing the HTTP requests using annotations (@GET, @POST, etc.).
- Create a Retrofit object with a base URL and a converter (e.g., GsonConverterFactory).
- Create an implementation of the interface through Retrofit.
- Call the desired method and handle the response (using enqueue for asynchronous calls).
Example:
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 api = retrofit.create(ApiService::class.java)
api.getUser("123").enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
if (response.isSuccessful) {
val user = response.body()
// handle data
}
}
override fun onFailure(call: Call<User>, t: Throwable) {
// handle error
}
})