Nearby lessons

79 of 125

Java - URL and URLConnection

📌 What You Will Learn
  • How two programs on different computers talk to each other
  • The client-server model
  • Socket programming with ServerSocket and Socket
  • The difference between TCP and UDP
  • The InetAddress class

URL and URLConnection is a core concept of the Java language. This lesson explains URL and URLConnection with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

URL and URLConnection

Java can also fetch content from a web address using the URL class:

Example01
JCode Cell
1import java.net.*;
2import java.io.*;
3 
4class URLDemo {
5 public static void main(String[] args) throws Exception {
6 URL u = new URL("https://www.google.com");
7 System.out.println("Protocol: " + u.getProtocol());
8 System.out.println("Host: " + u.getHost());
9 System.out.println("Port: " + u.getPort());
10 }
11}
Output
Protocol: https Host: www.google.com Port: -1
📝 Key Takeaways
  • Networking = programs on different computers exchanging data.
  • Client asks for a service; server provides it.
  • Server uses ServerSocket (accept) ; client uses Socket (connect).
  • TCP is reliable and ordered; UDP is fast but not guaranteed.
  • IP address finds the computer, port number finds the service.
  • InetAddress works with IPs; URL works with web addresses.
  • Modern apps use REST APIs over HTTP, but sockets teach the core idea.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2