4.1 Sử dụng Retrofit để tạo yêu cầu GET, POST, PUT, DELETE, v.v. đến các endpoint trong lập trình android

Trong lập trình android, để sử dụng Retrofit để tạo các yêu cầu GET, POST, PUT, DELETE và các phương thức HTTP khác đến các endpoint, bạn cần thực hiện các bước sau:

  1. Thêm Retrofit vào file build.gradle (Module app):
groovy
dependencies {
    // ...
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // (hoặc sử dụng converter khác tùy chọn)
}
  1. Tạo interface mô tả các yêu cầu API. Ví dụ, tạo một interface có tên là ApiService:
java
import retrofit2.Call;
import retrofit2.http.*;

public interface ApiService {

    @GET("endpoint")
    Call<ResponseBody> getData();

    @POST("endpoint")
    Call<ResponseBody> postData(@Body RequestBody requestBody);

    @PUT("endpoint/{id}")
    Call<ResponseBody> putData(@Path("id") int id, @Body RequestBody requestBody);

    @DELETE("endpoint/{id}")
    Call<ResponseBody> deleteData(@Path("id") int id);
}
  1. Tạo một instance của Retrofit và cấu hình nó trong class của bạn:
java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://your-base-url.com/api/";

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
  1. Sử dụng Retrofit để gửi yêu cầu tới endpoint trong class của bạn:
java
ApiService apiService = RetrofitClient.getClient().create(ApiService.class);

// Gửi yêu cầu GET
Call<ResponseBody> callGet = apiService.getData();
callGet.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        if (response.isSuccessful()) {
            // Xử lý dữ liệu từ response.body()
        } else {
            // Xử lý lỗi
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        // Xử lý lỗi kết nối
    }
});

// Gửi yêu cầu POST
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), yourJsonData);
Call<ResponseBody> callPost = apiService.postData(requestBody);
// Tiếp tục thực hiện enqueue() và xử lý kết quả tương tự như ví dụ trên

// Tương tự, bạn có thể gửi các yêu cầu PUT, DELETE và các phương thức khác tới các endpoint bằng cách gọi tương ứng trong ApiService.

Trong ví dụ trên, bạn cần thay đổi BASE_URL thành địa chỉ URL thực tế của API bạn muốn gọi và điều chỉnh các phương thức và đối số trong ApiService để phù hợp với API của bạn.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top