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