Junior
What is Retrofit and how is it used in Android development?
sobes.tech AI
Answer from AI
Retrofit is a type-safe HTTP client for Android and Java. It simplifies interaction with REST APIs by using annotations to describe requests.
Main advantages:
- Type safety: Requests and responses are represented as Java (or Kotlin) objects, reducing runtime errors.
- Ease of use: Declaring HTTP methods with annotations makes the code more readable and maintainable.
- Configurability: Easily add interceptors for logging, authentication, and other tasks.
- Integration with converters: Supports various converters for parsing responses (JSON, XML, etc.) out of the box (e.g., Gson, Jackson).
Usage:
-
Adding dependencies:
// build.gradle (app level) dependencies { implementation 'com.squareup.retrofit2:retrofit:<latest_version>' // Choose a converter for your data (here an example for Gson) implementation 'com.squareup.retrofit2:converter-gson:<latest_version>' } -
Defining the API interface: Create a Java/Kotlin interface that declares all API endpoints using annotations.
// ApiService.java import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import java.util.List; public interface ApiService { @GET("users/{userId}") // GET request to URL "users/{userId}" Call<User> getUser(@Path("userId") int userId); // @Path for inserting value into URL @GET("posts") // GET request to URL "posts" Call<List<Post>> getPosts(); } // User.java (example POJO for response) public class User { private int id; private String name; // getters and setters } // Post.java (example POJO for response) public class Post { private int id; private int userId; private String title; private String body; // getters and setters } -
Creating Retrofit instance:
// RetrofitClient.java import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitClient { private static final String BASE_URL = "https://api.example.com/"; // Your API's base URL private static Retrofit retrofit; public static Retrofit getRetrofitInstance() { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) // Set base URL .addConverterFactory(GsonConverterFactory.create()) // Add converter .build(); } return retrofit; } public static ApiService getApiService() { return getRetrofitInstance().create(ApiService.class); // Create API service instance } } -
Making requests:
// In Activity, Fragment, or ViewModel import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; // ... ApiService apiService = RetrofitClient.getApiService(); // Asynchronous request to get user by ID Call<User> userCall = apiService.getUser(1); userCall.enqueue(new Callback<User>() { // enqueue for asynchronous execution in another thread @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful() && response.body() != null) { User user = response.body(); // Handle the received user } else { // Handle error (e.g., response.code(), response.errorBody()) } } @Override public void onFailure(Call<User> call, Throwable t) { // Handle network error or other exceptions t.printStackTrace(); } }); // Asynchronous request to get list of posts Call<List<Post>> postsCall = apiService.getPosts(); postsCall.enqueue(new Callback<List<Post>>() { @Override public void onResponse(Call<List<Post>> call, Response<List<Post>> response) { if (response.isSuccessful() && response.body() != null) { List<Post> posts = response.body(); // Handle list of posts } else { // Handle error } } @Override public void onFailure(Call<List<Post>> call, Throwable t) { // Handle error t.printStackTrace(); } });
Retrofit abstracts low-level HTTP details, allowing you to focus on application logic.