Android Ağ İstekleri: Retrofit ve OkHttp ile API Bağlantısı
Android uygulamalarında sunucuyla iletişim kurmak neredeyse zorunlu. Retrofit ve OkHttp bu işi kolaylaştıran, birbirini tamamlayan iki kütüphanedir. Retrofit HTTP isteklerini tanımlamayı ve yönetmeyi basitleştirirken, OkHttp alt katmanda bağlantı, zaman aşımı ve yeniden deneme gibi işleri halleder.
İlk adım build.gradle dosyasına bağımlılıkları eklemek:
1dependencies {2implementation 'com.squareup.retrofit2:retrofit:2.9.0'3implementation 'com.squareup.retrofit2:converter-gson:2.9.0'4implementation 'com.squareup.okhttp3:okhttp:4.10.0'5implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0'6}Retrofit için bir interface oluştur. Bu, API endpoint'lerini ve isteklerin nasıl yapılacağını tanımlar:
1interface ApiService {2@GET("users/{id}")3suspend fun getUser(@Path("id") userId: Int): Response<User>45@POST("users")6suspend fun createUser(@Body user: User): Response<User>7}89data class User(10val id: Int,11val name: String,12val email: String13)OkHttp istemcisini özelleştir, ardından Retrofit'e bağla:
1val okHttpClient = OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).addInterceptor(HttpLoggingInterceptor().apply {2level = HttpLoggingInterceptor.Level.BODY3}).build()45val retrofit = Retrofit.Builder().baseUrl("https://api.example.com/").client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build()67val apiService = retrofit.create(ApiService::class.java)ViewModelinde istek yap ve hataları yakala:
1viewModelScope.launch {2try {3val response = apiService.getUser(1)4if (response.isSuccessful) {5val user = response.body()6println("Kullanıcı: ${user?.name}")7} else {8println("Hata: ${response.code()} - ${response.message()}")9}10} catch (e: IOException) {11println("Ağ hatası: ${e.message}")12} catch (e: Exception) {13println("Bilinmeyen hata: ${e.message}")14}15}Beklenen çıktı:
1Kullanıcı: Ali Yılmazveya hata durumunda:
1Ağ hatası: Unable to resolve host- Timeout ayarı: OkHttp ile bağlantı zaman aşımını kontrol et; çok kısa ayarlamak isteklerin başarısız olmasına neden olur.
- Logging: HttpLoggingInterceptor sadece geliştirme sırasında BODY seviyesinde tutulmalı; üretimde NONE olsun.
- Hata türleri: IOException ağ problemini, HttpException API hatasını, diğer Exception'lar parsing hatalarını gösterir.
Retrofit coroutine desteği ile asenkron işler kolayca yapılır. OkHttp'nin interceptor mekanizması ise otomatik başlık ekleme, token yenileme gibi ortak işler için idealdir.
0 yorum