Overview
Android applications frequently communicate with remote servers to fetch, send, or synchronize data. Networking on Android involves making HTTP requests, handling responses, performing serialization/deserialization (e.g., JSON), and managing threading to avoid blocking the UI. This document explains core networking concepts in Android and demonstrates how to perform network operations using modern libraries.
Networking Challenges on Android
Key considerations when implementing networking include:
- Asynchronous execution: Networking on the main thread is prohibited; use background threads or asynchronous APIs.
- Thread safety: Avoid UI thread blockage by using concurrency utilities (AsyncTask is deprecated; prefer Executors, Coroutines, or libraries with built-in async support).
- Security: Use HTTPS, certificate pinning, and proper error handling for network reliability.
- Data parsing: Convert raw responses (JSON/XML) into usable data models.
Core Networking APIs
HttpURLConnection (Built-in)
HttpURLConnection is part of the JDK and available on Android without external dependencies. It’s low-level and requires manual connection management.
Sample GET Request:
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
// Handle the result
}
connection.disconnect();
While HttpURLConnection is reliable, it requires verbose code for common tasks (headers, retries, JSON parsing), motivating the use of higher-level libraries.
Modern Networking Libraries
To simplify networking, use libraries that provide cleaner APIs, built-in async support, and serialization integration.
OkHttp (Efficient Low-Level Client)
OkHttp is a widely used HTTP client that manages connection pooling, retries, caching, and request/response handling.
Add Dependency:
implementation 'com.squareup.okhttp3:okhttp:4.11.0'
GET Request with OkHttp:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
// Handle network error
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful() && response.body() != null) {
String responseData = response.body().string();
// Parse the response
}
}
});
OkHttp handles asynchronous execution internally and avoids UI thread blocking.
Retrofit (Declarative REST Client)
Retrofit builds on OkHttp and adds automatic request mapping, response parsing with converters (e.g., Gson), and clean interfaces for API definitions.
Add Dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Define API Interface:
public interface ApiService {
@GET("users")
Call<List<User>> getUsers();
}
Initialize Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Make an API Call:
Call<List<User>> call = apiService.getUsers();
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
if (response.isSuccessful()) {
List<User> users = response.body();
// Use parsed data
}
}
@Override
public void onFailure(Call<List<User>> call, Throwable t) {
// Log or handle error
}
});
Retrofit simplifies network code by hiding low-level details and handling JSON parsing automatically via converters.
JSON Parsing
Most modern REST APIs return data in JSON format. The recommended approach in Android is to parse JSON into model objects.
Gson Example (with Retrofit):
public class User {
private int id;
private String name;
private String email;
// Getters and setters
}
Retrofit’s GsonConverterFactory handles the JSON → Java mapping automatically.
Handling Timeouts and Retries
Configure timeouts with OkHttp:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
For retries, OkHttp can intercept failures and retry based on custom policies or integrate with libraries like RetryInterceptor.
Background Execution
Perform networking off the main thread using:
- OkHttp / Retrofit built-in async
- Executors / ThreadPools
- Kotlin Coroutines
- WorkManager for scheduled or guaranteed background tasks
Retrofit + Coroutines Example:
interface ApiService {
@GET("users")
suspend fun getUsers(): List<User>
}
// In a coroutine scope
lifecycleScope.launch {
try {
val users = apiService.getUsers()
// Update UI
} catch (e: Exception) {
// Handle error
}
}
Coroutines provide concise syntax and structured concurrency, reducing boilerplate.
Security Considerations
When performing network operations:
- Always use HTTPS
- Validate certificates (certificate pinning with OkHttp)
- Do not store sensitive tokens in plain text
- Refresh and revoke tokens securely when needed
- Implement proper error handling and logging (don’t expose internals)
Testing Network Code
Testing improves reliability:
- Unit tests: Mock API responses with tools like MockWebServer
- Integration tests: Run real endpoints in staging environments
- UI tests: Verify UI behavior during success and failure states
Testing networking improves resilience against regressions.
Best Practices
- Avoid long operations on the UI thread
- Gracefully handle connectivity changes and timeouts
- Provide user feedback during network operations (loading indicators)
- Cache responses where appropriate for offline support (OkHttp caching)
- Monitor analytics for network error trends


