Networking & APIs
Networking
Android apps ច្រើនត្រូវការទំនាក់ទំនងជាមួយ internet ដើម្បីទាញយកទិន្នន័យពី servers (APIs)។ Networking គឺជា core skill សម្រាប់ modern apps!
🌐 Network Communication Flow
┌─────────────────┐ │ Android App │ ──► Send HTTP Request └────────┬────────┘ (GET, POST, PUT, DELETE) │ ▼ Internet │ ┌────────▼────────┐ │ Web Server │ ──► Process request │ (API/Backend) │ Execute logic └────────┬────────┘ │ ▼ Response │ ┌────────▼────────┐ │ Android App │ ──► Parse JSON/XML │ (Display data) │ Update UI └─────────────────┘
📡 HTTP Request Methods
Method | Purpose | Example |
---|---|---|
GET | Retrieve data (read-only) | Get user list, Get post by ID |
POST | Create new resource | Create user, Submit form |
PUT | Update entire resource | Update user profile |
PATCH | Update partial resource | Update user email only |
DELETE | Delete resource | Delete user account |
📚 Android Networking Libraries
Library | Pros | Cons | When to Use |
---|---|---|---|
Volley | ✅ Easy to use ✅ Built-in caching ✅ Request queue |
❌ Limited features ❌ Verbose code |
Simple APIs, Quick tasks |
Retrofit | ✅ Type-safe ✅ Clean syntax ✅ Powerful |
❌ Learning curve ❌ More setup |
✅ RESTful APIs (Recommended) |
OkHttp | ✅ Low-level control ✅ HTTP/2 support ✅ WebSocket |
❌ More code ❌ Manual parsing |
Custom protocols, WebSockets |
🆚 Volley vs Retrofit (Detailed)
Feature | Volley | Retrofit |
---|---|---|
Syntax | ⚠️ Verbose, callback hell | ✅ Clean, interface-based |
JSON Parsing | ❌ Manual | ✅ Automatic (Gson/Moshi) |
Type Safety | ❌ String-based | ✅ Type-safe models |
Request/Response | ⚠️ JSONObject/JSONArray | ✅ POJOs (User, Post objects) |
Error Handling | ⚠️ Manual parsing | ✅ Structured callbacks |
Caching | ✅ Built-in | ✅ Via OkHttp interceptor |
File Upload | ⚠️ Complex | ✅ Simple |
Recommendation | Legacy apps, Simple tasks | ✅ Modern apps (Use this!) |
📊 Response Status Codes
Code Range | Meaning | Common Codes |
---|---|---|
2xx Success | ✅ Request succeeded | 200 OK, 201 Created, 204 No Content |
3xx Redirection | 🔄 Further action needed | 301 Moved, 304 Not Modified |
4xx Client Error | ❌ Client mistake | 400 Bad Request, 401 Unauthorized, 404 Not Found |
5xx Server Error | ⚠️ Server problem | 500 Internal Error, 503 Service Unavailable |
🔐 Network Security
Security Practice | Why Important |
---|---|
🔒 Use HTTPS | Encrypt data in transit (not HTTP!) |
🔑 API Keys | Don't hardcode in code (use BuildConfig) |
📌 Certificate Pinning | Prevent man-in-the-middle attacks |
⏱️ Timeouts | Handle slow/failed connections |
🔄 Retry Logic | Handle temporary network failures |
⚠️ Permission Required: ត្រូវបន្ថែម <uses-permission android:name="android.permission.INTERNET"/>
ក្នុង AndroidManifest.xml!
✅ Best Practice: ប្រើ Retrofit + OkHttp + Gson សម្រាប់ modern Android apps! មិនត្រូវធ្វើ network calls នៅលើ main thread!
Java Code
Click "Run" to execute the Java code