How to perform network requests using Retrofit?
sobes.tech AI
Answer from AI
-
Adding dependencies: In the module's build.gradle, add Retrofit and a converter (e.g., Gson).
dependencies { implementation 'com.squareup.retrofit2:retrofit:2.11.0' implementation 'com.squareup.retrofit2:converter-gson:2.11.0' } -
Creating API interface: Define an interface with Retrofit annotations describing HTTP methods, paths, and request parameters.
public interface ApiService { @GET("users/{id}") Call<User> getUser(@Path("id") int userId); @POST("users") Call<User> createUser(@Body User user); } -
Creating Retrofit instance: Initialize Retrofit with a base URL and a converter.
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") // Base URL .addConverterFactory(GsonConverterFactory.create()) // Using Gson converter .build(); -
Creating API service instance: Obtain an instance of the API interface from the created Retrofit.
ApiService apiService = retrofit.create(ApiService.class); -
Executing a request: Call the interface method to perform the request. There are two main ways:
-
Synchronous: (Better to avoid on the main UI thread)
try { Response<User> response = apiService.getUser(123).execute(); if (response.isSuccessful()) { User user = response.body(); // Handle data } else { // Handle errors } } catch (IOException e) { // Handle network errors } -
Asynchronous: (Recommended for UI thread)
apiService.getUser(123).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { User user = response.body(); // Handle data on main thread } else { // Handle errors } } @Override public void onFailure(Call<User> call, Throwable t) { // Handle network errors } });
-
-
Data models: Create data model classes (POJO) for automatic JSON to Java object conversion using a converter (e.g., Gson).
public class User { private int id; private String name; // getters and setters } -
Network access permission: Don't forget to add the permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET"/>