Ответ
Retrofit — это HTTP-клиент для Android, упрощающий работу с REST API.
Основные шаги:
- Добавление зависимостей в
build.gradle:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
- Создание интерфейса API с аннотациями:
interface ApiService {
@GET("posts/{id}")
suspend fun getPost(@Path("id") postId: Int): Response<Post>
}
- Создание Retrofit-клиента:
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
- Вызов API:
val api = retrofit.create(ApiService::class.java)
val response = api.getPost(1) // suspend-функция, вызывается в корутине
Дополнительно:
- Используйте
suspendдля корутин. - Обрабатывайте ошибки через
try-catchилиResult-обёртки. - Для логирования добавьте
HttpLoggingInterceptorиз OkHttp.