Junior — Middle
How is the Retrofit library integrated into a project?
sobes.tech AI
Answer from AI
To integrate the Retrofit library into an Android project, you need to follow several steps:
- Add the dependency to your app module's
build.gradlefile:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// To work with JSON, usually add a converter, for example Gson:
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
-
Sync your project with Gradle.
-
Create an interface describing the HTTP requests using Retrofit annotations, for example:
public interface ApiService {
@GET("users/{id}")
Call<User> getUser(@Path("id") int userId);
}
- Create a Retrofit instance and configure it:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
- Use
apiServiceto perform requests and handle responses.
Thus, the integration involves adding dependencies, creating an API interface, and initializing Retrofit with the necessary parameters.