Network interaction and communications are the foundation of any modern mobile application working with remote data. In this article we will cover REST API, GraphQL, HTTP/HTTPS, WebSocket, популярные библиотеки (Retrofit, OkHttp, URLSession, Alamofire, Ktor, Dio), а также кэширование, офлайн-режим, пагинацию и безопасность соединений (SSL Pinning, TLS). This material is suitable for beginner developers who want to understand the network stack of mobile applications. For more details, see the HTTP overview from MDN.
Key Highlights
Choosing the API type is the first decision that affects the architecture of the entire application's network communications. Let's look at three main approaches.
REST (Representational State Transfer) is an architectural style based on HTTP methods GET, POST, PUT, PATCH, DELETE. Each resource has a unique URL (endpoint). REST is simple to cache, intuitive, and widely supported. Responses are usually returned in JSON format. For mobile applications, REST remains the de facto standard due to its simplicity and compatibility.
// Пример REST запроса через Retrofit interface ApiService { @GET("users/{id}") suspend fun getUser(@Path("id") id: Int): User }
GraphQL is a query language from Facebook (Meta) where the client specifies the response structure. Single endpoint, flexible queries, no overfetching (excess data) or underfetching (insufficient data). GraphQL is especially useful for complex nested data (e.g., user + their posts + comments). Disadvantages: complex caching, steeper learning curve.
WebSocket is a full-duplex communication protocol over TCP. After connection establishment (via HTTP handshake), both sides can send messages at any time. Used for chats, notifications, quotes, real-time games. In mobile apps, WebSocket is often combined with REST: REST for CRUD, WebSocket for real-time updates.
| Characteristic | REST API | GraphQL | WebSocket |
|---|---|---|---|
| Transport | HTTP/HTTPS | HTTP/HTTPS | TCP (после HTTP upgrade) |
| Data Format | JSON/XML | JSON (запрос и ответ) | Любой (JSON, Protobuf, текст) |
| Direction | Unidirectional (client → server) | Одностороннее | Bidirectional (full-duplex) |
| Caching | Built-in (HTTP cache) | Complex (requires Persisted Queries) | Not applicable |
| Typical Use | CRUD, lists, details | Complex nested data | Chats, notifications, live data |
Understanding the transport layer is essential for diagnosing network problems and optimizing communication performance.
HTTP (HyperText Transfer Protocol) is an application-layer protocol for hypertext transfer. HTTPS is HTTP over TLS/SSL, providing encryption. All modern mobile applications must use HTTPS because Apple and Google require secure connections (App Transport Security in iOS, network_security_config in Android).
TCP/IP is a reliable protocol with connection establishment, delivery guarantee, and packet ordering. Used for HTTP, WebSocket, email. UDP is fast but unreliable (no delivery confirmation). Used for streaming, VoIP, games where speed matters more than guaranteed delivery of every packet.
HTTP headers control caching (Cache-Control, ETag, Last-Modified), data format (Content-Type: application/json), authentication (Authorization: Bearer). Proper header handling is critical for performance: ETag and Last-Modified prevent reloading unchanged data.
Android offers several popular libraries for network communications. The choice depends on project requirements.
Retrofit (by Square) is a type-safe HTTP client for Android and Kotlin. Turns HTTP API into a Kotlin/Java interface. Works on top of OkHttp and supports coroutines, RxJava and Call adapters. Retrofit is the standard for Android development.
OkHttp is a low-level HTTP client from Square. Used as the foundation for Retrofit, but can also be used independently. OkHttp provides Interceptor (for logging, headers, retries), HTTP/2 multiplexing, automatic connection recovery and connection pooling.
Ktor Client is a multiplatform HTTP client from JetBrains for Kotlin Multiplatform Mobile. Supports Android, iOS, Web, Desktop. Native support for coroutines, serialization (kotlinx.serialization) and plugins (logging, authentication, WebSocket).
Volley is an HTTP library from Google, popular in legacy projects. Simple to set up, automatically manages request queue, supports caching. However, Volley is not recommended for new projects — Retrofit and OkHttp provide more features and integrate better with modern Android stack.
At IT Sectr we use the Retrofit + OkHttp combination for most Android projects with custom Interceptors for logging, retries and authentication. For KMM projects we choose Ktor Client.
iOS developers can use native URLSession or third-party libraries for network communications.
URLSession is Apple's native framework for HTTP requests. Supports background downloads (background URLSession), WebSocket, delegation protocols, cache management via URLCache. Since iOS 15, URLSession supports async/await, making network work more convenient.
func fetchUser(id: Int) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
Alamofire is the most popular third-party HTTP library for iOS. Provides a convenient API on top of URLSession: request chaining, automatic JSON conversion, validation, progress tracking, Multipart Upload. Alamofire is especially popular in Objective-C projects and when migrating from it to Swift.
For Flutter and React Native there are their own popular HTTP clients for network communications.
Dio is a powerful HTTP client for Flutter with support for Interceptor, FormData, caching, timeouts and retry policies. Dio is used in most Flutter projects as the main networking library.
Axios is an HTTP client for JavaScript/TypeScript working in React Native. Provides a convenient API for requests, interceptors, automatic JSON transformation and request cancellation via CancelToken.
Network communication security is a critical topic for mobile applications handling personal data.
TLS (Transport Layer Security) is an encryption protocol, successor to SSL. Ensures data confidentiality, integrity and authentication. All mobile applications should use TLS 1.2 or 1.3. Android and iOS prohibit unsecured connections (HTTP) by default.
SSL Pinning is a mechanism where the app checks the server certificate against a pre-stored certificate or public key. This protects against MITM attacks even if the CA is compromised. Implemented via OkHttp (Android) with CertificatePinner or via URLSession (iOS) with URLSessionDelegate. OWASP Mobile Top 10 рекомендует SSL Pinning для приложений, работающих с финансовыми или медицинскими данными.
Modern mobile applications must work with unstable network connections. Caching and offline mode strategies are key to good UX with limited server communications.
HTTP caching uses Cache-Control headers (max-age, no-cache), ETag and Last-Modified. OkHttp and URLSession support caching out of the box. Additionally, Room or Core Data can be used for database-level caching.
Offline-First is an approach where the app first loads data from a local source (cache, DB), then updates from the server. Key components: local storage (Room, SQLite, Core Data), sync manager (WorkManager for Android), network monitoring (ConnectivityManager, NWPathMonitor).
Pagination is used for efficient loading of large lists. Main strategies:
The Android Paging 3 library simplifies pagination implementation with Room, Network and coroutines support. In iOS, UITableViewDiffableDataSource + pagination via URLSession is the standard approach. At IT Sectr we use Paging 3 for Android and Combine-based pagination for iOS.
With unstable connections, a retry strategy is needed: exponential backoff, jitter, maximum retry count. For file uploads, Multipart Upload (large files) or Chunked Transfer Encoding (streaming) is used. Libraries: OkHttp Interceptor for retries, Alamofire MultipartFormData for file uploads.
Frequently Asked Questions
REST API uses HTTP methods to work with resources via endpoints. GraphQL is a query language where the client chooses the fields. REST is simpler for caching, GraphQL is more efficient for complex nested data.
Android: Retrofit + OkHttp, Ktor, Volley. iOS: URLSession (native), Alamofire. Flutter: Dio, http. React Native: Axios, fetch. The choice depends on the ecosystem.
SSL Pinning is a mechanism where the app checks the server certificate against a stored certificate or public key. Protects against MITM attacks when CA is compromised.
Offline-First: data is first loaded from local cache, then updated from the server. Room/SQLite for cache, WorkManager for background sync, ConnectivityManager/NWPathMonitor for network monitoring.
Cursor pagination — more reliable than offset-based for mobile apps. Offset pagination (page/limit) is unstable when adding records. Cursor-based with infinite scroll is recommended.
Summary
Развићемо мобилну апликацију под кључ
IT Sectr креира iOS и Android апликације за стартапе и предузећа од 2017. године. Саветоваћемо вас и предложити најбоље решење.