Networking (HTTP, REST, Retrofit, OkHttp & Serialization)
Build robust networking layers using HTTP protocols, RESTful APIs, Retrofit, OkHttp, and modern serialization libraries.
Module 13: Networking (HTTP, REST, Retrofit, OkHttp & Serialization)
Learning Objectives
By the end of this module, you’ll understand:
- How the Internet works (high level)
- Client-Server Architecture
- HTTP protocol
- HTTPS & TLS
- REST APIs
- HTTP methods
- Status codes
- Headers
- Request/Response lifecycle
- JSON
- Serialization & Deserialization
- Retrofit architecture
- OkHttp internals
- Interceptors
- Authentication
- Timeouts
- Caching
- Error handling
- Modern Android networking architecture
Part 1 — The Internet at a High Level
Suppose your app displays weather.
Where does the weather data come from?
Not from the phone.
Instead:
Phone
↓
Internet
↓
Weather Server
↓
Database
↓
Response
↓
Phone
The phone requests information.
The server responds.
This is called the Client-Server Model.
1. Client vs Server
Client
The client requests data.
Examples:
- Android App
- Chrome
- Firefox
- Postman
Server
The server provides data.
Examples:
- Amazon servers
- Google servers
- Netflix servers
The server owns the data.
The client asks for it.
Real Example
Instagram.
Instagram App
↓
Request Feed
↓
Instagram Server
↓
Posts
↓
App Displays Feed
Your phone doesn’t store every Instagram post.
It asks the server.
Part 2 — HTTP
How does the client communicate?
Using HTTP.
HTTP stands for:
HyperText Transfer Protocol
It defines how two computers communicate.
Think of it as a common language.
Imagine two people.
One speaks only English.
One speaks only Japanese.
Communication fails.
HTTP gives both sides the same language.
HTTP Request
Every network call begins with a request.
Example:
GET /users
Conceptually:
Android
↓
HTTP Request
↓
Server
HTTP Response
Server replies.
Server
↓
HTTP Response
↓
Android
Simple.
Everything on the Internet follows this pattern.
Request–Response Cycle
User Click
↓
ViewModel
↓
Repository
↓
Retrofit
↓
OkHttp
↓
Internet
↓
Server
↓
Response
↓
Repository
↓
ViewModel
↓
UI
This is the complete networking flow in a modern Android app.
Part 3 — HTTP Methods
Methods tell the server what you want.
GET
Retrieve data.
Example:
GET /products
Meaning:
Give me products.
No data is modified.
POST
Create something.
Example:
POST /users
Meaning:
Create a new user.
PUT
Replace an existing resource.
Example:
PUT /users/5
Replace user 5 entirely with the new representation.
PATCH
Update part of a resource.
Example:
PATCH /users/5
Only change selected fields (for example, the email).
DELETE
Remove data.
DELETE /users/5
Delete user 5.
CRUD Mapping
| Database | HTTP |
|---|---|
| Create | POST |
| Read | GET |
| Update | PUT / PATCH |
| Delete | DELETE |
Part 4 — URL Anatomy
Example:
https://api.shop.com/products/25?sort=price
Break it apart:
https://
Protocol
↓
api.shop.com
Host
↓
products
Path
↓
25
Resource ID
↓
sort=price
Query Parameter
Each part has a specific meaning.
Part 5 — HTTPS
HTTP sends data in plaintext.
Bad.
Anyone intercepting traffic could read it.
HTTPS adds:
TLS Encryption
Flow:
Phone
↓
Encrypted Data
↓
Server
Nobody in the middle can easily read or modify the contents.
Modern Android apps should use HTTPS for network communication.
Part 6 — HTTP Headers
Headers contain metadata.
Example:
Authorization
Content-Type
Accept
User-Agent
Think of them like labels on a package.
The package contains the data.
The label explains the package.
Authorization Header
Example:
Bearer Token
Server checks:
Is this user authenticated?
If yes:
Return data.
Content-Type
Example:
application/json
Meaning:
The request or response body contains JSON.
Part 7 — HTTP Status Codes
Server always returns a status code.
200 OK
Everything succeeded.
201 Created
New resource created successfully.
204 No Content
Operation succeeded.
No response body.
400 Bad Request
Client sent invalid data.
401 Unauthorized
Authentication required or invalid credentials.
403 Forbidden
Authenticated.
Not allowed.
404 Not Found
Resource doesn’t exist.
500 Internal Server Error
Server failed.
Usually not your fault.
Categories
| Range | Meaning |
|---|---|
| 2xx | Success |
| 3xx | Redirection |
| 4xx | Client Error |
| 5xx | Server Error |
Part 8 — REST APIs
REST is an architectural style.
Instead of:
getUsers.php
Modern APIs expose resources.
/users
/products
/orders
Each endpoint represents a resource.
HTTP methods define the action.
Example:
GET /users
POST /users
DELETE /users/15
Notice:
Same endpoint.
Different methods.
Part 9 — JSON
Servers rarely send Kotlin objects.
Instead:
{
"id": 5,
"name": "Alice"
}
JSON is simply text.
Android must convert it into Kotlin objects.
Serialization
Kotlin object
↓
JSON
Example:
User("Alice")
becomes
{
"name":"Alice"
}
Deserialization
Reverse process.
JSON
↓
Kotlin Object
Example:
{
"id":5
}
becomes
User(id=5)
Popular Serialization Libraries
- Kotlinx Serialization
- Moshi
- Gson (legacy but still widely used)
Today, many new Kotlin projects prefer Kotlinx Serialization or Moshi.
Part 10 — Retrofit
Retrofit is not an HTTP client.
This is one of the biggest misconceptions.
Retrofit is:
A type-safe HTTP client library built on top of OkHttp.
Architecture:
Retrofit
↓
OkHttp
↓
Socket
↓
Internet
Retrofit simplifies API definitions.
OkHttp performs the actual networking.
Example Interface
interface UserApi {
@GET("users")
suspend fun getUsers(): List<User>
}
Notice:
No implementation.
Retrofit generates it dynamically.
How Retrofit Works
Suppose:
api.getUsers()
Internally:
Dynamic Proxy
↓
Build HTTP Request
↓
OkHttp
↓
Internet
↓
JSON
↓
Deserializer
↓
User Objects
You call a Kotlin function.
Retrofit transforms it into an HTTP request.
Part 11 — OkHttp
Retrofit delegates all network operations to OkHttp.
Responsibilities:
- Open sockets
- Manage connections
- HTTPS
- Redirects
- Retries (limited, transport-level)
- Caching
- Interceptors
- HTTP/2 support
- Connection pooling
Retrofit focuses on APIs.
OkHttp focuses on networking.
Connection Pool
Without pooling:
Request
↓
New TCP Connection
↓
Close
Repeatedly.
Expensive.
Instead:
Request
↓
Reuse Existing Connection
Much faster.
Part 12 — Interceptors
One of OkHttp’s most powerful features.
Imagine every request needs:
Authorization
Content-Type
Language
Instead of adding them manually:
Use an interceptor.
Flow:
Request
↓
Interceptor
↓
Add Headers
↓
Continue
Centralized and reusable.
Logging Interceptor
Useful during development.
Logs:
- URL
- Headers
- Body (when enabled)
- Response
- Timing
Avoid verbose body logging in production, especially if sensitive information is involved.
Part 13 — Authentication
Most modern APIs use:
Bearer Token
Flow:
Login
↓
Receive Token
↓
Save Securely
↓
Send Header
↓
Server Validates
↓
Response
Every authenticated request includes:
Authorization: Bearer <token>
Refresh Tokens (Conceptual)
Tokens expire.
Flow:
Expired Token
↓
401
↓
Refresh Token
↓
New Access Token
↓
Retry Request
This is often handled by an OkHttp Authenticator.
Part 14 — Timeouts
What if the server never responds?
Without timeouts:
App waits forever.
OkHttp provides:
- Connect timeout
- Read timeout
- Write timeout
- Call timeout
Always configure sensible values for your use case.
Part 15 — Error Handling
Many things can fail.
No Internet
↓
DNS Failure
↓
Timeout
↓
401
↓
500
↓
Malformed JSON
Don’t assume every request succeeds.
Model success and failure explicitly.
A common approach:
Loading
↓
Success
↓
Error
The ViewModel exposes these states to the UI.
Part 16 — Modern Networking Architecture
Imagine loading products.
Compose Screen
↓
ViewModel
↓
Repository
↓
Retrofit
↓
OkHttp
↓
Internet
↓
Server
↓
JSON
↓
Deserializer
↓
Repository
↓
StateFlow
↓
Compose Recomposition
Notice how every module we’ve studied participates.
Part 17 — Caching
Suppose:
User opens:
Products
Again.
Without cache:
Phone
↓
Internet
↓
Server
Every time.
Wasteful.
With cache:
Phone
↓
Local Cache
↓
Internet Only If Needed
Caching reduces:
- Network usage
- Battery consumption
- Load times
Caching may happen in:
- OkHttp (HTTP cache)
- Room database
- Repository logic
- In-memory caches
Part 18 — Retry Strategies
Network requests fail.
Question:
Should you retry?
Depends.
Example:
Timeout
↓
Retry
↓
Success
Good.
But:
401 Unauthorized
↓
Retry Forever
Pointless.
Always distinguish transient failures from permanent ones.
Part 19 — Complete Request Lifecycle
Suppose user presses:
Refresh
Everything that happens:
Button Click
│
▼
ViewModel
│
▼
Repository
│
▼
Retrofit Interface
│
▼
Dynamic Proxy
│
▼
OkHttp
│
▼
Interceptor
│
▼
HTTPS Request
│
▼
Internet
│
▼
Server
│
▼
JSON Response
│
▼
Deserializer
│
▼
Repository
│
▼
StateFlow
│
▼
Compose UI
This is the end-to-end journey of a network request in a modern Android app.
Common Mistakes
❌ Calling Retrofit directly from the UI
Always go through a Repository (and often a Use Case).
❌ Ignoring HTTP status codes
A 200 and a 404 require different handling.
❌ Logging authentication tokens
Never print sensitive credentials in production logs.
❌ Assuming network availability
Handle offline scenarios gracefully.
❌ Performing networking on the Main Thread
Retrofit’s coroutine support already works well with background execution, but avoid blocking operations on the UI thread.
❌ Treating every failure the same
Differentiate between:
- Network unavailable
- Timeout
- Authentication failure
- Server error
- Data parsing error
Mental Model
Imagine ordering food.
Customer (UI)
│
▼
Waiter (ViewModel)
│
▼
Kitchen Manager (Repository)
│
▼
Chef (Retrofit)
│
▼
Kitchen Equipment (OkHttp)
│
▼
Restaurant (Server)
│
▼
Meal Returned
│
▼
Customer Eats
Each participant has one responsibility.
None of them tries to do everyone else’s job.
That’s exactly how modern Android networking is structured.
Best Practices
- Use Retrofit for API definitions.
- Let OkHttp handle networking details.
- Prefer HTTPS for all production APIs.
- Keep authentication logic centralized (interceptors/authenticators).
- Expose network results as UI state through the ViewModel.
- Handle loading, success, and error explicitly.
- Cache strategically to improve responsiveness.
- Avoid leaking transport-layer details into the UI.
Interview Questions
- Explain the client-server model.
- What’s the difference between HTTP and HTTPS?
- Compare GET, POST, PUT, PATCH, and DELETE.
- What are HTTP headers, and why are they useful?
- Explain common HTTP status codes.
- What is REST?
- What is the difference between serialization and deserialization?
- How are Retrofit and OkHttp related?
- What are OkHttp interceptors used for?
- How would you architect networking in an MVVM Android application?
Module 13 Summary
You now understand the complete networking stack used in modern Android applications:
- HTTP defines how clients and servers communicate.
- HTTPS secures that communication with TLS.
- REST organizes APIs around resources.
- JSON is the common data exchange format.
- Serialization converts between JSON and Kotlin objects.
- Retrofit provides a type-safe API interface.
- OkHttp performs the actual network operations.
- Interceptors and Authenticators centralize cross-cutting concerns.
- Repositories coordinate networking with the rest of the application architecture.
At this point, you can trace a request from a button tap all the way to data appearing on the screen.
Next Module: Local Data Persistence (Room, SQLite, DataStore & Offline-First)
Module 14 will explore how Android stores data on the device.
We’ll cover:
- Internal vs External Storage
- Files and storage APIs
- SharedPreferences vs DataStore
- SQLite fundamentals
- Room ORM internals
- Entities, DAOs, and Migrations
- Relationships and Transactions
- Room with Coroutines and Flow
- Offline-first architecture
- Caching strategies
- Syncing local and remote data
This module completes the data layer by teaching how professional Android apps work even when the network is unavailable.