Sobes.tech
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:

  1. Add the Retrofit dependency to your project.
  2. Create an interface describing the HTTP requests using annotations (@GET, @POST, etc.).
  3. Create a Retrofit object with a base URL and a converter (e.g., GsonConverterFactory).
  4. Create an implementation of the interface through Retrofit.
  5. 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
    }
})