Sobes.tech
Middle

How to perform network requests using the Retrofit library?

sobes.tech AI

Answer from AI

  1. 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
    
  2. 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, @Body are annotations for request parameters.
    • Call<T> is the return type for asynchronous or synchronous requests.
  3. 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);
    
  4. 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
    }
    
  5. Handle the response: In onResponse methods or after successful execute. Check the response status (response.isSuccessful()) and extract data (response.body()). Handle errors in onFailure or in the catch block 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.

How to perform network requests using the Retrofit… - sobes.tech