Modern Android applications frequently communicate with remote servers to retrieve, create, update, and delete data.
Whether you’re developing an e-commerce application, social media platform, finance tracker, news reader, or productivity tool, reliable networking is essential.
Android developers commonly use Retrofit and OkHttp to implement HTTP-based APIs.
Retrofit simplifies API declarations and response conversion, while OkHttp manages the underlying HTTP communication.
Together with Kotlin Coroutines, Hilt, ViewModel, StateFlow, and Jetpack Compose, these libraries provide a strong foundation for modern Android networking.
In this tutorial, we’ll learn Retrofit and OkHttp step by step and build a practical Product Explorer application.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What REST APIs are
- How HTTP requests work
- Retrofit fundamentals
- OkHttp fundamentals
- Retrofit vs OkHttp
- GET, POST, PUT, PATCH, and DELETE
- Path and query parameters
- HTTP headers
- JSON serialization
- Kotlin Coroutines with Retrofit
- OkHttp interceptors
- Authentication headers
- Network timeouts
- HTTP error handling
- IOException and HttpException
- Hilt dependency injection
- Repository Pattern
- MVVM integration
- StateFlow and UI state
- Jetpack Compose integration
- Network security
- Unit testing
- Production best practices
1. What Is a REST API?
REST stands for Representational State Transfer.
A REST API is a web interface that follows REST architectural principles and commonly communicates using HTTP.
Android applications use APIs to exchange information with backend services.
Example
A shopping application may request:
GET https://dummyjson.com/products
The server returns a JSON response containing product information.
Example JSON
{
"products": [
{
"id": 1,
"title": "Product A",
"price": 99.99
}
],
"total": 1,
"skip": 0,
"limit": 30
}
This is an illustrative response structure.
The actual response depends on the API.
Basic Networking Flow
Android Application
|
| HTTP Request
v
REST API
|
| JSON Response
v
Retrofit
|
v
Repository
|
v
ViewModel
|
v
Jetpack Compose
2. Understanding HTTP Methods
REST APIs commonly use the following HTTP methods.
| Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | Fetch products |
| POST | Create a resource | Add a product |
| PUT | Replace a resource | Replace product details |
| PATCH | Partially update a resource | Change product price |
| DELETE | Delete a resource | Remove a product |
GET Example
GET /products
POST Example
POST /products/add
Content-Type: application/json
{
"title": "Android Phone",
"price": 499
}
PATCH Example
PATCH /products/1
Content-Type: application/json
{
"price": 399
}
Important
HTTP methods describe the requested operation, but actual behavior depends on the backend.
A demonstration API may simulate modifications without permanently storing them.
3. What Is Retrofit?
Retrofit is a type-safe HTTP client library for Android and Java developed by Square.
It allows developers to define HTTP endpoints using Kotlin interfaces and annotations.
Example
interface ProductApi {
@GET("products")
suspend fun getProducts(): ProductResponse
}
Retrofit generates the implementation of this interface.
Benefits
- Declarative API definitions
- Kotlin Coroutine support
- JSON conversion
- Request parameters
- Custom headers
- Multipart requests
- Integration with OkHttp
- Easier API testing
4. What Is OkHttp?
OkHttp is an HTTP client library developed by Square.
It handles lower-level HTTP operations such as:
- HTTP connections
- Connection pooling
- TLS
- Timeouts
- Redirects
- HTTP caching
- Interceptors
- Request and response processing
Retrofit typically uses OkHttp as its underlying HTTP client.
Retrofit and OkHttp Architecture
Android App
|
v
Retrofit
|
v
Request Conversion
|
v
OkHttp
|
v
HTTPS Server
|
v
JSON Response
|
v
Retrofit
|
v
Kotlin Models
5. Retrofit vs OkHttp
| Feature | Retrofit | OkHttp |
|---|---|---|
| Main purpose | API interface abstraction | HTTP communication |
| HTTP requests | Annotation-based | Request-based |
| JSON conversion | Through converters | Manual or additional libraries |
| Interceptors | Uses OkHttp | Native support |
| Connection pooling | Through OkHttp | Built-in |
| Coroutine integration | Suspend API methods | Requires additional integration |
| Typical use | REST API services | HTTP client configuration |
Recommendation
Use Retrofit for structured REST APIs.
Configure OkHttp for connection behavior, interceptors, authentication, and timeouts.
6. Add Retrofit and OkHttp Dependencies
Create a Kotlin Android project with Jetpack Compose.
Add the following dependencies to your app module.
dependencies {
implementation(
"com.squareup.retrofit2:retrofit:<retrofit-version>"
)
implementation(
"com.squareup.retrofit2:converter-gson:<retrofit-version>"
)
implementation(
"com.squareup.okhttp3:okhttp:<okhttp-version>"
)
implementation(
"com.squareup.okhttp3:logging-interceptor:<okhttp-version>"
)
implementation(
"org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>"
)
}
Replace placeholders with compatible stable library versions.
Internet Permission
Add this permission outside the application element in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
Android applications need this permission to access the network.
7. Create Your First Retrofit API
Let’s use DummyJSON, a public demonstration API.
Base URL:
https://dummyjson.com/
API Interface
import retrofit2.http.GET
interface ProductApi {
@GET("products")
suspend fun getProducts(): ProductResponse
}
Explanation
@GET defines the HTTP method and relative endpoint.
The suspend keyword allows the API function to be called from a coroutine.
Retrofit handles the HTTP request and response conversion.
8. Understanding JSON Serialization
APIs commonly return JSON data.
Retrofit uses converters to transform JSON into Kotlin objects.
Popular options include:
- Gson
- Kotlin Serialization
- Moshi
Example JSON
{
"id": 1,
"title": "Smartphone",
"price": 299.99
}
Kotlin Data Class
data class ProductDto(
val id: Int,
val title: String,
val price: Double
)
Important
For financial calculations, avoid relying on binary floating-point arithmetic.
Convert prices to an appropriate integer minor-unit representation or use a decimal type where required.
9. Creating a Retrofit Instance
Retrofit requires a base URL and a converter for JSON responses.
val retrofit = Retrofit.Builder()
.baseUrl("https://dummyjson.com/")
.addConverterFactory(
GsonConverterFactory.create()
)
.build()
Create API Service
val productApi = retrofit.create(
ProductApi::class.java
)
Explanation
Retrofit generates the implementation of ProductApi.
Best Practice
Avoid constructing Retrofit every time a screen opens.
Reuse appropriately configured Retrofit and OkHttp instances.
10. GET Requests with Query Parameters
Many APIs support pagination and filtering.
Example
GET /products?limit=10&skip=20
Retrofit
@GET("products")
suspend fun getProducts(
@Query("limit") limit: Int,
@Query("skip") skip: Int
): ProductResponse
Usage
val response = productApi.getProducts(
limit = 10,
skip = 20
)
Explanation
@Query adds query parameters to the request URL.
Retrofit handles parameter encoding.
11. Path Parameters with @Path
Some APIs include identifiers in their endpoint paths.
Example
GET /products/5
Retrofit
@GET("products/{id}")
suspend fun getProduct(
@Path("id") productId: Int
): ProductDto
Usage
val product = productApi.getProduct(
productId = 5
)
Explanation
@Path replaces a named placeholder in the endpoint URL.
12. POST Requests with @Body
POST requests commonly send data to a server.
Request Model
data class CreateProductRequest(
val title: String,
val price: Double
)
API Method
@POST("products/add")
suspend fun createProduct(
@Body request: CreateProductRequest
): ProductDto
Usage
val product = productApi.createProduct(
CreateProductRequest(
title = "Android Phone",
price = 499.0
)
)
Explanation
@Body serializes the request object into the HTTP request body using the configured converter.
DummyJSON simulates product creation; it should not be treated as permanent storage.
13. PUT and PATCH Requests
PUT commonly replaces a resource representation.
PATCH commonly applies partial updates.
PUT
@PUT("products/{id}")
suspend fun replaceProduct(
@Path("id") productId: Int,
@Body request: UpdateProductRequest
): ProductDto
PATCH
@PATCH("products/{id}")
suspend fun updateProduct(
@Path("id") productId: Int,
@Body request: UpdateProductRequest
): ProductDto
Request Model
data class UpdateProductRequest(
val title: String? = null,
val price: Double? = null
)
Important
Actual PATCH semantics and nullable-field serialization depend on the backend API contract.
Do not assume null and omitted fields mean the same thing.
14. DELETE Requests
DELETE requests ask the server to remove a resource.
Example
@DELETE("products/{id}")
suspend fun deleteProduct(
@Path("id") productId: Int
): Response<Unit>
Explanation
Response<Unit> allows the caller to inspect the HTTP status without requiring a response body model.
Important
Some APIs return a JSON representation of the deleted resource.
Choose the return type according to the actual API response contract.
15. Understanding HTTP Headers
Headers provide metadata about requests and responses.
Common headers include:
- Authorization
- Accept
- Content-Type
- User-Agent
- Cache-Control
Static Header
@Headers("Accept: application/json")
@GET("products")
suspend fun getProducts(): ProductResponse
Dynamic Header
@GET("profile")
suspend fun getProfile(
@Header("Authorization") token: String
): UserProfileDto
Usage
api.getProfile(
token = "Bearer $accessToken"
)
Best Practice
For shared authentication requirements, use an OkHttp interceptor rather than manually passing the same header to every endpoint.
16. What Are OkHttp Interceptors?
An interceptor can inspect, modify, or observe HTTP requests and responses.
Common uses include:
- Authentication headers
- Logging
- Custom request metadata
- Cache policy
- Network diagnostics
Example
class AppHeaderInterceptor : Interceptor {
override fun intercept(
chain: Interceptor.Chain
): Response {
val request = chain.request()
.newBuilder()
.header("X-App-Platform", "Android")
.build()
return chain.proceed(request)
}
}
Explanation
The interceptor adds a custom header to outgoing requests.
17. Authentication Interceptor
Applications often use access tokens to authenticate requests.
Example
interface TokenProvider {
fun getAccessToken(): String?
}
class AuthInterceptor(
private val tokenProvider: TokenProvider
) : Interceptor {
override fun intercept(
chain: Interceptor.Chain
): Response {
val token = tokenProvider.getAccessToken()
val requestBuilder = chain.request()
.newBuilder()
if (!token.isNullOrBlank()) {
requestBuilder.header(
"Authorization",
"Bearer $token"
)
}
return chain.proceed(
requestBuilder.build()
)
}
}
Explanation
The interceptor reads the current token and attaches it to the request.
Security Considerations
- Never hardcode production access tokens.
- Avoid logging Authorization headers.
- Use HTTPS.
- Keep tokens out of publicly accessible storage.
- Avoid sending authentication headers to unrelated hosts.
- Use an appropriate token refresh strategy.
Important
OkHttp application interceptors are synchronous.
If token retrieval requires suspend functions, design an appropriate synchronization or caching strategy rather than using blocking coroutine bridges indiscriminately.
18. HTTP Logging Interceptor
Logging is useful during development.
Example
val loggingInterceptor =
HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BASIC
} else {
HttpLoggingInterceptor.Level.NONE
}
redactHeader("Authorization")
redactHeader("Cookie")
}
Explanation
BASIC logging records request and response lines.
BODY logging may expose sensitive payloads and should be avoided unless carefully controlled.
Best Practice
Disable sensitive HTTP logging in production builds.
19. Configuring Network Timeouts
Network operations should not wait indefinitely.
Example
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.callTimeout(45, TimeUnit.SECONDS)
.build()
Explanation
Connect Timeout: Maximum time allowed to establish a connection.
Read Timeout: Maximum inactivity interval while reading data.
Write Timeout: Maximum inactivity interval while writing data.
Call Timeout: Overall timeout for the complete HTTP call.
Important
Timeout values should be selected based on your backend, expected payload sizes, and user experience requirements.
There is no single configuration suitable for every application.
20. Understanding HTTP Status Codes
| Status Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 408 | Request Timeout |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
| 502 | Bad Gateway |
| 503 | Service Unavailable |
Best Practice
Do not show raw HTTP status codes to users without meaningful explanations.
Convert technical failures into appropriate application error states.
21. Handling Network Errors
Common network errors include:
- No internet connection
- DNS failure
- Connection timeout
- HTTP 401
- HTTP 404
- HTTP 500
- Invalid JSON response
- Unexpected server response
Example
suspend fun loadProducts(): Result<ProductResponse> {
return try {
Result.success(
api.getProducts()
)
} catch (exception: CancellationException) {
throw exception
} catch (exception: IOException) {
Result.failure(exception)
} catch (exception: HttpException) {
Result.failure(exception)
}
}
Important
Coroutine cancellation should not be converted into an ordinary application error.
Always preserve cancellation behavior.
22. Creating a Network Result Model
A sealed result type can represent application-level networking outcomes.
sealed interface NetworkResult<out T> {
data class Success<T>(
val data: T
) : NetworkResult<T>
data class Error(
val message: String,
val statusCode: Int? = null
) : NetworkResult<Nothing>
}
Benefits
- Explicit success and failure handling
- Easier ViewModel integration
- Predictable UI states
- Centralized error representation
Best Practice
Use typed error categories when different errors require different recovery actions.
Practical Mini-Project: Product Explorer with Retrofit, OkHttp, Hilt & Jetpack Compose
Now let’s build a Product Explorer application.
Features
- Fetch products from DummyJSON
- Display product names and prices
- Search products locally
- Refresh the product list
- Handle loading and error states
- Configure OkHttp
- Use Hilt Dependency Injection
- Implement Repository Pattern
- Manage UI state using StateFlow
- Render data using Jetpack Compose
Technology Stack
- Kotlin
- Jetpack Compose
- Material 3
- Retrofit
- OkHttp
- Gson
- Hilt
- ViewModel
- StateFlow
- Kotlin Coroutines
- MVVM
23. Recommended Project Structure
com.example.productexplorer/
│
├── ProductExplorerApplication.kt
├── MainActivity.kt
│
├── data/
│ ├── remote/
│ │ ├── ProductApi.kt
│ │ ├── ProductDto.kt
│ │ └── ProductResponse.kt
│ │
│ └── repository/
│ └── ProductRepositoryImpl.kt
│
├── domain/
│ ├── model/
│ │ └── Product.kt
│ └── repository/
│ └── ProductRepository.kt
│
├── di/
│ ├── NetworkModule.kt
│ └── RepositoryModule.kt
│
└── presentation/
├── ProductUiState.kt
├── ProductViewModel.kt
└── ProductScreen.kt
24. Step 1 — Configure Hilt
Use the Hilt setup introduced in Article 44.
Ensure the app has:
- Hilt Gradle plugin
- Hilt runtime dependency
- Hilt KSP compiler
- ViewModel integration
- Retrofit
- OkHttp
- Gson converter
Application Class
package com.example.productexplorer
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ProductExplorerApplication : Application()
Register the Application class in AndroidManifest.xml.
Also add INTERNET permission.
25. Step 2 — Create Product DTO
File: data/remote/ProductDto.kt
package com.example.productexplorer.data.remote
data class ProductDto(
val id: Int,
val title: String,
val description: String,
val price: Double,
val thumbnail: String?
)
Explanation
ProductDto represents product information returned by DummyJSON.
26. Step 3 — Create ProductResponse
File: data/remote/ProductResponse.kt
package com.example.productexplorer.data.remote
data class ProductResponse(
val products: List<ProductDto>,
val total: Int,
val skip: Int,
val limit: Int
)
Explanation
The response contains product records and pagination metadata.
27. Step 4 — Create Domain Product Model
File: domain/model/Product.kt
package com.example.productexplorer.domain.model
data class Product(
val id: Int,
val name: String,
val description: String,
val price: Double
)
Explanation
The domain model represents product information used by the application.
It does not need to match the API response structure exactly.
For real commerce applications, use an appropriate decimal or integer minor-unit representation for monetary values.
28. Step 5 — Create DTO Mapper
Add the following mapper to ProductDto.kt.
import com.example.productexplorer.domain.model.Product
fun ProductDto.toDomain(): Product {
return Product(
id = id,
name = title,
description = description,
price = price
)
}
Explanation
The mapper converts remote data into an application-level model.
This reduces coupling between API response formats and the rest of the application.
29. Step 6 — Create ProductApi
File: data/remote/ProductApi.kt
package com.example.productexplorer.data.remote
import retrofit2.http.GET
interface ProductApi {
@GET("products")
suspend fun getProducts(): ProductResponse
}
Explanation
The API interface defines the endpoint used by Product Explorer.
30. Step 7 — Create NetworkModule
File: di/NetworkModule.kt
package com.example.productexplorer.di
import com.example.productexplorer.BuildConfig
import com.example.productexplorer.data.remote.ProductApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
private const val BASE_URL =
"https://dummyjson.com/"
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
val logging = HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BASIC
} else {
HttpLoggingInterceptor.Level.NONE
}
}
return OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
}
@Provides
@Singleton
fun provideRetrofit(
client: OkHttpClient
): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(
GsonConverterFactory.create()
)
.build()
}
@Provides
fun provideProductApi(
retrofit: Retrofit
): ProductApi {
return retrofit.create(
ProductApi::class.java
)
}
}
Explanation
Hilt provides:
- OkHttpClient
- Retrofit
- ProductApi
Important
BuildConfig generation must be enabled if your project configuration does not generate it automatically.
31. Step 8 — Create ProductRepository Interface
File: domain/repository/ProductRepository.kt
package com.example.productexplorer.domain.repository
import com.example.productexplorer.domain.model.Product
interface ProductRepository {
suspend fun getProducts(): List<Product>
}
Explanation
The ViewModel depends on this repository contract.
32. Step 9 — Implement ProductRepository
File: data/repository/ProductRepositoryImpl.kt
package com.example.productexplorer.data.repository
import com.example.productexplorer.data.remote.ProductApi
import com.example.productexplorer.data.remote.toDomain
import com.example.productexplorer.domain.model.Product
import com.example.productexplorer.domain.repository.ProductRepository
import javax.inject.Inject
class ProductRepositoryImpl @Inject constructor(
private val api: ProductApi
) : ProductRepository {
override suspend fun getProducts(): List<Product> {
return api.getProducts()
.products
.map { it.toDomain() }
}
}
Explanation
The repository performs the network request and maps DTOs to domain models.
It does not expose Retrofit details to the ViewModel.
33. Step 10 — Create RepositoryModule
File: di/RepositoryModule.kt
package com.example.productexplorer.di
import com.example.productexplorer.data.repository.ProductRepositoryImpl
import com.example.productexplorer.domain.repository.ProductRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
abstract fun bindProductRepository(
implementation: ProductRepositoryImpl
): ProductRepository
}
Explanation
Hilt can now supply ProductRepositoryImpl when ProductRepository is requested.
34. Step 11 — Create ProductUiState
File: presentation/ProductUiState.kt
package com.example.productexplorer.presentation
import com.example.productexplorer.domain.model.Product
data class ProductUiState(
val products: List<Product> = emptyList(),
val searchQuery: String = "",
val isLoading: Boolean = false,
val errorMessage: String? = null
)
Explanation
The state represents the information required by ProductScreen.
35. Step 12 — Create ProductViewModel
File: presentation/ProductViewModel.kt
package com.example.productexplorer.presentation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.productexplorer.domain.repository.ProductRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@HiltViewModel
class ProductViewModel @Inject constructor(
private val repository: ProductRepository
) : ViewModel() {
private val _uiState =
MutableStateFlow(ProductUiState())
val uiState: StateFlow<ProductUiState> =
_uiState.asStateFlow()
init {
loadProducts()
}
fun loadProducts() {
if (_uiState.value.isLoading) return
viewModelScope.launch {
_uiState.update {
it.copy(
isLoading = true,
errorMessage = null
)
}
try {
val products = repository.getProducts()
_uiState.update {
it.copy(
products = products,
isLoading = false
)
}
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
val message = when (exception) {
is java.net.SocketTimeoutException ->
"Request timed out. Please try again."
is java.io.IOException ->
"Network unavailable. Check your connection."
is retrofit2.HttpException ->
"Server error: ${exception.code()}"
else ->
"Unable to load products."
}
_uiState.update {
it.copy(
isLoading = false,
errorMessage = message
)
}
}
}
}
fun updateSearchQuery(query: String) {
_uiState.update {
it.copy(searchQuery = query)
}
}
}
Explanation
The ViewModel manages:
- Loading state
- Product data
- Search query
- Error state
It does not create Retrofit or access OkHttp directly.
Best Practice
For larger applications, move error classification into a reusable data-layer component.
Avoid duplicating exception handling across multiple ViewModels.
36. Step 13 — Create ProductScreen
File: presentation/ProductScreen.kt
package com.example.productexplorer.presentation
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.productexplorer.domain.model.Product
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProductScreen(
viewModel: ProductViewModel
) {
val uiState by viewModel.uiState
.collectAsStateWithLifecycle()
val filteredProducts = remember(
uiState.products,
uiState.searchQuery
) {
uiState.products.filter { product ->
product.name.contains(
uiState.searchQuery,
ignoreCase = true
)
}
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text("Product Explorer")
}
)
}
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
.padding(16.dp),
verticalArrangement =
Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = uiState.searchQuery,
onValueChange = viewModel::updateSearchQuery,
label = {
Text("Search Products")
},
modifier = Modifier.fillMaxWidth(),
singleLine = true
)
Button(
onClick = viewModel::loadProducts,
enabled = !uiState.isLoading,
modifier = Modifier.fillMaxWidth()
) {
Text("Refresh Products")
}
if (uiState.isLoading) {
LinearProgressIndicator(
modifier = Modifier.fillMaxWidth()
)
}
uiState.errorMessage?.let { message ->
Text(
text = message,
color = MaterialTheme.colorScheme.error
)
}
Text(
text = "Products: ${filteredProducts.size}",
style = MaterialTheme.typography.titleMedium
)
if (
!uiState.isLoading &&
uiState.errorMessage == null &&
filteredProducts.isEmpty()
) {
Text("No products found")
}
LazyColumn(
verticalArrangement =
Arrangement.spacedBy(8.dp)
) {
items(
items = filteredProducts,
key = { it.id }
) { product ->
ProductItem(product)
}
}
}
}
}
Explanation
The screen observes UI state using collectAsStateWithLifecycle().
It filters the loaded product list based on the user’s search query.
Important
This example searches only products already loaded into memory.
For large catalogs, use server-side search and pagination.
37. Step 14 — Create ProductItem
Add this composable to ProductScreen.kt.
@Composable
fun ProductItem(
product: Product
) {
Card(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement =
Arrangement.spacedBy(8.dp)
) {
Text(
text = product.name,
style = MaterialTheme.typography.titleMedium
)
Text(
text = product.description,
style = MaterialTheme.typography.bodyMedium
)
Text(
text = "$${product.price}",
style = MaterialTheme.typography.titleSmall
)
}
}
}
Explanation
ProductItem is a stateless composable.
It receives product data and renders the product card.
38. Step 15 — Create MainActivity
File: MainActivity.kt
package com.example.productexplorer
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.productexplorer.presentation.ProductScreen
import com.example.productexplorer.presentation.ProductViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(
savedInstanceState: Bundle?
) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
val productViewModel: ProductViewModel =
viewModel()
ProductScreen(
viewModel = productViewModel
)
}
}
}
}
Explanation
Hilt creates ProductViewModel and supplies ProductRepository.
The repository receives ProductApi.
ProductApi uses Retrofit and OkHttp.
39. Expected Application UI
+--------------------------------+
| Product Explorer |
| |
| [ Search Products ] |
| |
| [ Refresh Products ] |
| |
| Products: 30 |
| |
| +----------------------------+ |
| | Product Name | |
| | Product description | |
| | $99.99 | |
| +----------------------------+ |
| |
| +----------------------------+ |
| | Another Product | |
| | Product description | |
| | $149.99 | |
| +----------------------------+ |
| |
| +----------------------------+ |
| | More Products | |
| | Product description | |
| | $79.99 | |
| +----------------------------+ |
+--------------------------------+
The actual product names, descriptions, prices, and count depend on the API response.
40. How the Complete Networking Architecture Works
Step 1: Application Launch
MainActivity displays ProductScreen.
Step 2: ViewModel Initialization
ProductViewModel calls loadProducts().
Step 3: Repository Request
The ViewModel calls ProductRepository.
Step 4: Retrofit Request
ProductRepositoryImpl calls ProductApi.
Step 5: OkHttp Communication
OkHttp sends the HTTPS request.
Step 6: API Response
The server returns JSON data.
Step 7: Response Conversion
Gson converts JSON into Kotlin DTOs.
Step 8: Domain Mapping
The repository maps DTOs to domain models.
Step 9: StateFlow Update
The ViewModel updates ProductUiState.
Step 10: Compose Recomposition
Jetpack Compose displays the latest products.
Complete Architecture
Jetpack Compose
|
v
ProductViewModel
|
v
ProductRepository
|
v
ProductRepositoryImpl
|
v
ProductApi
|
v
Retrofit
|
v
OkHttp
|
v
DummyJSON API
Hilt supplies the required dependencies across these layers.
41. Adding Retry Support
Network requests can fail temporarily.
A retry action allows users to request data again.
Example
Button(
onClick = viewModel::loadProducts
) {
Text("Try Again")
}
Automatic Retry Considerations
Automatic retries should be used carefully.
Avoid retrying requests indefinitely.
For production applications:
- Use bounded retry attempts.
- Apply exponential backoff when appropriate.
- Respect server rate limits.
- Avoid retrying non-idempotent operations blindly.
- Respect Retry-After headers when applicable.
- Preserve coroutine cancellation.
Important
A POST request may create a resource more than once if retried without appropriate server-side safeguards.
42. Understanding HTTP Caching
OkHttp supports HTTP caching through a configured Cache.
Example
val cache = Cache(
directory = File(context.cacheDir, "http_cache"),
maxSize = 10L * 1024L * 1024L
)
val client = OkHttpClient.Builder()
.cache(cache)
.build()
Explanation
OkHttp can reuse eligible cached HTTP responses based on caching headers and request directives.
Important
Configuring Cache does not mean every response becomes available offline.
Caching behavior depends on HTTP cache policies and response headers.
For reliable offline-first applications, consider Room as the application’s local source of truth.
43. Handling Authentication Expiration
Authentication tokens may expire.
A production application may need to:
- Detect authentication failure.
- Refresh the access token.
- Retry the original request.
- Update stored credentials.
- Sign the user out when refresh fails.
OkHttp provides an Authenticator interface that can participate in handling authentication challenges.
Important
Token refresh logic must avoid infinite retry loops.
It must also handle concurrent requests, refresh failures, and secure credential storage.
Do not send credentials to unintended hosts.
44. Testing Retrofit APIs
Retrofit networking can be tested using MockWebServer.
Add Test Dependency
testImplementation(
"com.squareup.okhttp3:mockwebserver:<okhttp-version>"
)
Example
@Test
fun `getProducts parses API response`() = runTest {
val server = MockWebServer()
server.start()
try {
server.enqueue(
MockResponse()
.setResponseCode(200)
.setBody(
"""
{
"products": [],
"total": 0,
"skip": 0,
"limit": 30
}
""".trimIndent()
)
)
val retrofit = Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(
GsonConverterFactory.create()
)
.build()
val api = retrofit.create(
ProductApi::class.java
)
val result = api.getProducts()
assertEquals(0, result.products.size)
} finally {
server.shutdown()
}
}
Explanation
MockWebServer simulates an HTTP server.
It allows developers to test:
- Successful responses
- HTTP errors
- Invalid JSON
- Timeouts
- Request headers
- Request bodies
Without making requests to a real backend.
45. Testing the Repository
Repositories should be testable independently from the UI.
Example Fake API
class FakeProductApi : ProductApi {
override suspend fun getProducts(): ProductResponse {
return ProductResponse(
products = listOf(
ProductDto(
id = 1,
title = "Test Product",
description = "Test Description",
price = 100.0,
thumbnail = null
)
),
total = 1,
skip = 0,
limit = 30
)
}
}
Repository Test
@Test
fun `repository maps product DTOs`() = runTest {
val repository = ProductRepositoryImpl(
api = FakeProductApi()
)
val products = repository.getProducts()
assertEquals(1, products.size)
assertEquals(
"Test Product",
products.first().name
)
}
Explanation
The repository can be tested without a real network request.
46. Common Retrofit and OkHttp Mistakes
Mistake 1: Creating Retrofit in Every Screen
Reuse configured instances.
Mistake 2: Performing Network Operations Directly in Composables
Use repositories and ViewModels.
Mistake 3: Ignoring Coroutine Cancellation
Rethrow CancellationException.
Mistake 4: Logging Sensitive Data
Never expose authentication tokens or private information in logs.
Mistake 5: Ignoring HTTP Status Codes
Handle relevant API errors explicitly.
Mistake 6: Using Unlimited Retries
Apply bounded retries and backoff.
Mistake 7: Hardcoding Production Secrets
Keep secrets out of application source code and distributed binaries.
Mistake 8: Assuming HTTP Cache Guarantees Offline Support
Use a persistent data layer for offline-first requirements.
Mistake 9: Ignoring Timeouts
Configure timeouts according to application requirements.
Mistake 10: Using Floating-Point Values for Financial Calculations
Use appropriate monetary representations.
47. Production Best Practices
Follow these recommendations:
- Use Retrofit for structured REST APIs.
- Use OkHttp for HTTP configuration.
- Prefer HTTPS endpoints.
- Configure appropriate timeouts.
- Use Hilt for dependency management.
- Keep networking inside the data layer.
- Map DTOs to application models.
- Use Kotlin Coroutines for asynchronous operations.
- Preserve cancellation.
- Model loading, success, and error states.
- Use StateFlow for observable UI state.
- Use lifecycle-aware collection.
- Avoid exposing sensitive information in logs.
- Implement authentication securely.
- Handle token expiration carefully.
- Use bounded retries.
- Respect API rate limits.
- Use pagination for large datasets.
- Cache data appropriately.
- Test HTTP behavior with MockWebServer.
- Test repositories with fake dependencies.
- Monitor network performance and failures.
48. Retrofit and OkHttp Quick Reference
| Concept | Purpose |
|---|---|
| Retrofit | Type-safe API interface |
| OkHttp | HTTP communication |
| @GET | Retrieve resources |
| @POST | Create resources |
| @PUT | Replace resources |
| @PATCH | Partially update resources |
| @DELETE | Delete resources |
| @Path | URL path parameter |
| @Query | Query parameter |
| @Header | Request header |
| @Body | Request body |
| Interceptor | Inspect or modify HTTP traffic |
| Authenticator | Handle authentication challenges |
| HttpLoggingInterceptor | HTTP diagnostics |
| IOException | I/O-related failure |
| HttpException | Non-successful HTTP response from a body-returning Retrofit suspend call |
| MockWebServer | HTTP testing |
| StateFlow | Observable UI state |
| Hilt | Dependency injection |
49. Practical Exercises
Exercise 1: Basic GET Request
Retrieve products using Retrofit.
Exercise 2: Query Parameters
Implement pagination with limit and skip.
Exercise 3: Product Details
Retrieve one product using @Path.
Exercise 4: POST Request
Create a sample product using @Body.
Exercise 5: Custom Headers
Add an application header using an interceptor.
Exercise 6: Authentication
Create a token-based authentication interceptor.
Exercise 7: Error Handling
Display appropriate messages for network and HTTP failures.
Exercise 8: Product Explorer
Build the complete Product Explorer application.
Exercise 9: MockWebServer
Test successful and failed HTTP responses.
Exercise 10: Offline Caching
Extend the application with Room-based local persistence.
50. Frequently Asked Questions
What is Retrofit in Android?
Retrofit is a type-safe HTTP client library used to define and execute API requests.
What is OkHttp?
OkHttp is an HTTP client that handles network connections, requests, responses, interceptors, and caching.
What is the difference between Retrofit and OkHttp?
Retrofit provides an API abstraction, while OkHttp handles the underlying HTTP communication.
Does Retrofit support Kotlin Coroutines?
Yes. Retrofit supports suspend functions.
What is an OkHttp interceptor?
An interceptor can inspect or modify HTTP requests and responses.
How do I add authentication headers?
Use @Header for individual requests or an OkHttp interceptor for shared authentication behavior.
How should I handle API errors?
Handle transport failures, HTTP errors, parsing failures, and cancellation appropriately.
Can Retrofit work with Hilt?
Yes. Hilt can provide Retrofit, OkHttpClient, and API service instances.
Can Retrofit work with Jetpack Compose?
Yes. Retrofit is typically used through repositories and ViewModels, with Compose observing UI state.
Does OkHttp support caching?
Yes. OkHttp supports HTTP caching when configured appropriately.
How can I test Retrofit without internet access?
Use MockWebServer to simulate API responses.
Is Retrofit suitable for production Android applications?
Yes. Retrofit and OkHttp are widely used for Android networking.
What We’ve Learned
In this tutorial, we explored:
- REST API fundamentals
- HTTP methods
- Retrofit configuration
- OkHttp configuration
- JSON conversion
- GET, POST, PUT, PATCH, and DELETE
- Path and query parameters
- HTTP headers
- Authentication interceptors
- Logging interceptors
- Network timeouts
- HTTP error handling
- Hilt integration
- Repository Pattern
- MVVM architecture
- StateFlow
- Jetpack Compose integration
- Practical Product Explorer application
- Retry strategies
- HTTP caching
- Authentication expiration
- MockWebServer testing
- Repository testing
- Production best practices
Retrofit and OkHttp provide a powerful foundation for Android networking.
By combining them with Kotlin Coroutines, Hilt, Repository Pattern, ViewModel, StateFlow, and Jetpack Compose, developers can build reliable, maintainable, and testable API-driven applications.
The key principle is simple:
Keep networking in the data layer, expose meaningful state to the UI, and handle failures as carefully as successful responses.
What’s Next?
In our next tutorial:
Article 47 — Kotlin Serialization in Android with Retrofit: JSON Parsing, Custom Serializers & Type-Safe APIs
You’ll learn:
- Kotlin Serialization fundamentals
- @Serializable annotation
- JSON encoding and decoding
- kotlinx.serialization.json.Json
- Retrofit converter integration
- Gson vs Kotlin Serialization
- Optional and nullable fields
- @SerialName
- Custom serializers
- Polymorphic serialization
- API response mapping
- Error handling
- Hilt integration
- Practical Android mini-project
- Testing serialization
- Production best practices
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.