Ответ
Для выполнения GET-запроса с Retrofit нужно:
- Создать интерфейс с аннотациями:
interface ApiService {
@GET("users/{id}")
suspend fun getUser(@Path("id") userId: Int): User
@GET("posts")
suspend fun getPosts(@Query("userId") userId: Int): List<Post>
}
- Создать экземпляр Retrofit:
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(ApiService::class.java)
- Вызвать метод (в корутине):
try {
val user = apiService.getUser(1)
val posts = apiService.getPosts(user.id)
} catch (e: Exception) {
// Обработка ошибок
}
Ключевые моменты:
@GET- указывает метод запроса@Path- подставляет значение в URL@Query- добавляет параметры запроса- Используйте suspend функции для корутин