Network ProgrammingUnit 511 min read
Java Networking Utilities & Classes: URL, HTTP, Cookies, and Utilities
Unit 5 of Network Programming: Explores Java’s built-in utilities for network operations, including URL/HTTP handling, cookies, response codes, and low-level networking classes like InetAddress, DatagramPacket, and MulticastSocket, with practical examples and code traces.
TAKEAWAYS:
- Java’s
java.netpackage provides high-level utilities likeURLandHttpURLConnectionto interact with web resources, simplifying HTTP requests and responses. - Cookies (
HttpCookie,CookieManager) enable session management in web applications, storing client-side data for personalized experiences (e.g., eSewa login tokens). - HTTP response codes (e.g.,
200 OK,404 Not Found) standardize server feedback, critical for debugging and error handling in client-server apps. - The
InetAddressclass resolves hostnames to IP addresses (e.g.,tufoshss.edu.np) and checks network connectivity, foundational for socket programming. - Low-level utilities like
DatagramPacketandMulticastSocketsupport UDP-based communication, used in real-time apps like WhatsApp status updates. - Thread-safe utilities (e.g.,
java.net.http.HttpClient) modernize networking, replacing legacy blocking I/O with asynchronous operations for scalability.
1. Java’s Networking Utilities Overview
Java’s java.net package offers high-level abstractions for common networking tasks, reducing boilerplate code. These utilities are used in:
- Web scraping (e.g., fetching Daraz product pages).
- API interactions (e.g., Khalti’s payment gateway).
- Network diagnostics (e.g., checking if
ntc.net.npis reachable).
Key Classes and Interfaces
| Class/Interface | Purpose | Example Use Case |
|---|---|---|
URL |
Represents a web resource (URL parsing, connection handling). | Fetching YouTube video metadata. |
HttpURLConnection |
Handles HTTP requests/responses (GET, POST, headers). | Submitting a Pathao ride request. |
CookieManager/HttpCookie |
Manages HTTP cookies for session persistence. | eSewa remembering user login. |
InetAddress |
Resolves hostnames to IPs (e.g., google.com → 142.250.190.46). |
Socket programming (Unit 2). |
DatagramPacket/Socket |
UDP-based communication (low-latency, connectionless). | WhatsApp status updates. |
MulticastSocket |
Supports multicast group communication (e.g., live streaming). | Ncell’s mobile app push notifications. |
2. Working with URLs and HTTP Connections
Java simplifies HTTP interactions using URL and HttpURLConnection.
Opening a URL Connection
- Parse a URL:
URL url = new URL("https://www.daraz.com.np/products"); - Open a connection:
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); - Read the response:
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); }
Example Trace: Fetching Daraz Product Data
Assume daraz.com.np returns HTML for a product page. The HttpURLConnection steps are:
- Request sent:
GET /products HTTP/1.1with headers (e.g.,User-Agent). - Server response:
HTTP/1.1 200 OK+ HTML body. - Client reads: Parses HTML to extract product details (e.g., price, reviews).
Visual: HTTP Request/Response Flow
sequenceDiagram
participant Client
participant DarazServer
Client->>DarazServer: GET /products\nHost: daraz.com.np\nUser-Agent: Java/1.8
DarazServer-->>Client: HTTP/1.1 200 OK\nContent-Type: text/html\n\n<html>...</html>3. HTTP Response Codes
Servers communicate status via 3-digit codes. Key examples:
| Code | Name | Meaning | Example Use Case |
|---|---|---|---|
| 200 | OK | Request succeeded. | Daraz showing product details. |
| 400 | Bad Request | Invalid syntax (e.g., missing headers). | Pathao API rejecting malformed data. |
| 404 | Not Found | Resource does not exist. | NTC website page deleted. |
| 500 | Internal Server Error | Server-side failure. | NEPSE API crashing during trading. |
Worked Example: Handling a 404
int responseCode = connection.getResponseCode();
if (responseCode == 404) {
System.err.println("Error: Page not found on NTC's website.");
}
4. Cookies in Java Networking
Cookies store client-side data (e.g., session IDs) across requests. Java uses:
HttpCookie: Represents a single cookie.CookieManager: Manages cookie storage/retrieval.
Example: eSewa Login Session
- Server sends a cookie:
HttpCookie cookie = new HttpCookie("session_id", "abc123"); cookie.setPath("/"); - Client stores and sends it:
CookieManager manager = new CookieManager(); manager.getCookieStore().add(new HttpCookie("session_id", "abc123"));
Visual: Cookie Flow in eSewa
sequenceDiagram
participant User
participant eSewaServer
User->>eSewaServer: POST /login\nusername=john\npassword=123
eSewaServer-->>User: HTTP/1.1 200 OK\nSet-Cookie: session_id=abc123
User->>eSewaServer: GET /dashboard\nCookie: session_id=abc1235. Low-Level Networking Utilities
For custom protocols (e.g., UDP-based apps), Java provides:
InetAddress: Resolve hostnames/IPs.DatagramPacket: Send/receive UDP datagrams.MulticastSocket: Join multicast groups.
Example: Checking NTC’s IP
InetAddress address = InetAddress.getByName("ntc.net.np");
System.out.println("IP: " + address.getHostAddress()); // Output: 117.247.100.100
UDP Datagram Example
DatagramSocket socket = new DatagramSocket();
byte[] buffer = "Hello Ncell!".getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
InetAddress.getByName("ncell.com.np"), 12345);
socket.send(packet);
Visual: UDP Packet Structure
+---------------------+---------------------+
| Header (8 bytes)| Payload (data) |
| Source Port (2) | "Hello Ncell!" (12) |
| Dest Port (2) | |
| IP Address (4) | |
| Checksum (2) | |
+---------------------+---------------------+
6. Thread-Safe Utilities (Java 11+)
Modern Java replaces blocking I/O with asynchronous utilities:
java.net.http.HttpClient: Non-blocking HTTP requests.CompletableFuture: Handles callbacks for async operations.
Example: Async Daraz Price Check
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://www.daraz.com.np/products"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
Comparison: Blocking vs. Non-Blocking
| Feature | Blocking I/O | Non-Blocking I/O (Java NIO) |
|---|---|---|
| Thread Model | One thread per connection. | Single thread handles many connections. |
| Performance | Scales poorly under load. | High throughput (e.g., Ncell’s app). |
| Java Class | HttpURLConnection |
HttpClient, AsynchronousSocketChannel |
| Use Case | Legacy systems (e.g., NEPSE APIs). | Modern apps (e.g., WhatsApp status). |
In the Real World
eSewa’s Cookie Management
- Idea: Uses
HttpCookieto store user session tokens after login. - How: When you log in, eSewa sends a
Set-Cookieheader with a session ID. Java’sCookieManagerpersists this cookie for subsequent requests (e.g., transferring money). - Real Impact: Without cookies, eSewa would require re-login for every transaction, degrading UX.
- Idea: Uses
Pathao’s API Error Handling
- Idea: Relies on HTTP response codes (e.g.,
404for unavailable drivers,503for server maintenance). - How: Pathao’s backend returns
404if no drivers are near your location. Java’sHttpURLConnectionchecksgetResponseCode()to display "No drivers available" to users. - Worked Example:
int status = connection.getResponseCode(); if (status == 404) { System.out.println("No drivers found. Try again later."); }
- Idea: Relies on HTTP response codes (e.g.,
Ncell’s Multicast Push Notifications
- Idea: Uses
MulticastSocketto send bulk updates (e.g., promotional messages) to all subscribed users efficiently. - How: Ncell’s server sends a multicast packet to a group address (e.g.,
239.0.0.1:1234). All subscribed phones (running Ncell’s app) receive the message without individual addressing. - Visual: Multicast Group Communication
sequenceDiagram participant NcellServer participant User1 participant User2 NcellServer->>User1: Multicast Packet (239.0.0.1:1234) NcellServer->>User2: Multicast Packet (239.0.0.1:1234)
- Idea: Uses
Exam Tip
Focus on these high-weight topics:
- URL/HTTP Handling: Know how to open connections, read responses, and parse headers. Expect a code snippet + trace question.
- Example: "Write a program to fetch and print the title of
https://www.youtube.com."
- Example: "Write a program to fetch and print the title of
- Cookies: Explain
CookieManagervs.HttpCookiewith a real-world example (e.g., eSewa).- Example: "How does a browser store cookies for
khalti.com?"
- Example: "How does a browser store cookies for
- HTTP Response Codes: Memorize 3–4 codes (200, 404, 500) and their meanings. Often paired with error-handling code.
- Example: "A client receives
403 Forbiddenfrom a bank’s API. What does this mean?"
- Example: "A client receives
- Low-Level Utilities: Differentiate
InetAddress,DatagramPacket, andMulticastSocket. Show a UDP packet structure in your answer.- Example: "Explain how
InetAddresshelps in resolvinggoogle.comto an IP."
- Example: "Explain how
- Async vs. Blocking I/O: Compare
HttpURLConnection(blocking) withHttpClient(non-blocking). Use a table like above.- Example: "Why does WhatsApp use non-blocking I/O for status updates?"
- URL/HTTP Handling: Know how to open connections, read responses, and parse headers. Expect a code snippet + trace question.
Common Pitfalls:
- Forgetting to call
connection.disconnect()after reading a URL (leaks resources). - Confusing
HttpURLConnection(HTTP-only) withSocket(generic TCP). - Not handling exceptions (e.g.,
MalformedURLException,IOException).
- Forgetting to call
Time Management:
- Spend 30% of time on URL/HTTP (high marks for code + trace).
- 20% on cookies (define classes + real example).
- 20% on low-level utilities (draw a UDP packet or multicast diagram).
- 10% each on async I/O and response codes (quick definitions).
Final Advice: Always include a code snippet + trace table for URL/HTTP questions. For cookies, draw the flow diagram (like the eSewa example above). Use tables for comparisons (e.g., blocking vs. non-blocking I/O).
Based on the TU BCA syllabus for Network Programming (CACS355), unit 5.
Discussion
Loading…