How to perform network requests using the Retrofit library?
sobes.tech AI
Answer from AI
-
Add dependency: In
build.gradle(app).// Retrofit implementation 'com.squareup.retrofit2:retrofit:<latest_version>' implementation 'com.squareup.retrofit2:converter-gson:<latest_version>' // or another converter -
Create API interface: Define methods for each network request.
interface ApiService { @GET("users/{id}") Call<User> getUser(@Path("id") int userId); @POST("users") Call<User> createUser(@Body User user); }@GET,@POST, and other annotations specify the HTTP method type."users/{id}"is the relative path to the resource.@Path,@Query,@Bodyare annotations for request parameters.Call<T>is the return type for asynchronous or synchronous requests.
-
Create Retrofit instance: Configure the base URL and add a converter.
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) // Use Gson for JSON parsing .build(); ApiService apiService = retrofit.create(ApiService.class); -
Make a request: Asynchronously or synchronously.
Asynchronous (recommended for UI thread):
Call<User> call = apiService.getUser(123); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { if (response.isSuccessful()) { User user = response.body(); // Handle successful response } else { // Handle error response (e.g., 404, 500) } } @Override public void onFailure(Call<User> call, Throwable t) { // Handle network error or exception } });Synchronous (do not use on UI thread):
try { Response<User> response = apiService.getUser(123).execute(); if (response.isSuccessful()) { User user = response.body(); // Handle successful response } else { // Handle error response } } catch (IOException e) { // Handle error } -
Handle the response: In
onResponsemethods or after successfulexecute. Check the response status (response.isSuccessful()) and extract data (response.body()). Handle errors inonFailureor in thecatchblock for synchronous requests.
Retrofit also supports integration with coroutines (using retrofit2:retrofit2-kotlin-coroutines-adapter), RxJava (using retrofit2:adapter-rxjava), and other libraries for asynchronous programming.