How is Retrofit used in Android?

Retrofit is a library used for performing HTTP network requests in Android. It simplifies the process of making network requests by providing an annotation-based approach to defining API interfaces and request parameters. It also supports features such as asynchronous network requests and file uploads.

Here are the main uses of Retrofit:

  1. Add dependency: Add Retrofit dependency in the build.gradle file of the project.
implementation 'com.squareup.retrofit2:retrofit:2.x.x'
  1. Create a Retrofit instance: Use Retrofit.Builder to create a Retrofit instance and specify the base URL for network requests.
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.example.com/") // 基础URL
    .build();
  1. Define API interfaces: Use Java interfaces to define API interfaces, and use annotations to mark request methods and request parameters.
public interface ApiService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}
  1. Create API instance: Use the Retrofit.create() method to create an API instance.
ApiService apiService = retrofit.create(ApiService.class);
  1. Initiate a network request: initiate a network request by calling methods from the API instance, and handle the request’s result using a Callback.
Call<List<Repo>> call = apiService.listRepos("octocat");
call.enqueue(new Callback<List<Repo>>() {
    @Override
    public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
        if (response.isSuccessful()) {
            List<Repo> repos = response.body();
            // 处理请求成功的结果
        } else {
            // 处理请求失败的结果
        }
    }

    @Override
    public void onFailure(Call<List<Repo>> call, Throwable t) {
        // 处理请求失败的结果
    }
});

By following the above steps, you can use Retrofit to make HTTP network requests and handle the results of success and failure. Additionally, you can use other annotations and methods to support different types of network requests, such as POST, PUT, DELETE, etc.

bannerAds