retrofit的基本使用
时间: 2024-04-20 14:16:49 浏览: 23
Retrofit 是一个用于 Android 和 Java 的 Type-Safe HTTP 客户端,它可以将 HTTP API 转换为 Java 接口。Retrofit 通过注解来描述 HTTP 请求和响应的结构,从而使得开发者可以使用 Java 接口来调用 API。
基本使用步骤如下:
1. 导入 Retrofit 库。在 build.gradle 文件中添加以下代码:
```
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
}
```
2. 定义 API 接口。通过 Java 接口的方式定义 API 接口,如:
```
public interface ApiService {
@GET("user/{id}")
Call<User> getUser(@Path("id") int userId);
}
```
3. 创建 Retrofit 实例。通过 Retrofit.Builder 创建 Retrofit 实例,如:
```
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
```
4. 创建 API 实例。通过 Retrofit.create() 方法创建 API 接口的实例,如:
```
ApiService apiService = retrofit.create(ApiService.class);
```
5. 发起请求。通过 API 接口实例来发起请求,如:
```
Call<User> call = apiService.getUser(userId);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
// 请求成功处理
}
@Override
public void onFailure(Call<User> call, Throwable t) {
// 请求失败处理
}
});
```
以上就是 Retrofit 的基本使用步骤。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)