Java URL & URI

Working with web addresses in Java

🔗 What are URLs and URIs?

URLs and URIs in Java represent web addresses and resource identifiers. URL provides connection capabilities while URI handles general resource identification for web applications and services.


// Basic URL example
URL url = new URL("https://www.example.com/page.html");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Path: " + url.getPath());
                                    

URL & URI Components

🌐

URL Class

Concrete web address with connection

URL url = new URL("https://example.com");
🏷️

URI Class

Abstract resource identifier

URI uri = new URI("https://example.com/path");
🔧

URL Components

Protocol, host, port, path, query

url.getProtocol(); // "https"
📡

URL Connection

Open connection to web resource

URLConnection conn = url.openConnection();

🔹 Working with URL Class

Create and manipulate URLs in Java:

import java.net.*;

public class URLExample {
    public static void main(String[] args) {
        try {
            // Create URL object
            URL url = new URL("https://www.example.com:8080/path/page.html?param=value#section");
            
            // Get URL components
            System.out.println("Full URL: " + url.toString());
            System.out.println("Protocol: " + url.getProtocol());
            System.out.println("Host: " + url.getHost());
            System.out.println("Port: " + url.getPort());
            System.out.println("Path: " + url.getPath());
            System.out.println("Query: " + url.getQuery());
            System.out.println("Fragment: " + url.getRef());
            System.out.println("Authority: " + url.getAuthority());
            
            // Default port handling
            int port = url.getPort();
            if (port == -1) {
                port = url.getDefaultPort();
            }
            System.out.println("Actual Port: " + port);
            
        } catch (MalformedURLException e) {
            System.out.println("Invalid URL: " + e.getMessage());
        }
    }
}

Output:

Full URL: https://www.example.com:8080/path/page.html?param=value#section

Protocol: https

Host: www.example.com

Port: 8080

Path: /path/page.html

Query: param=value

🔹 Working with URI Class

URI provides more flexible resource identification:

import java.net.*;

public class URIExample {
    public static void main(String[] args) {
        try {
            // Create URI object
            URI uri = new URI("https://api.example.com/users/123?format=json");
            
            // Get URI components
            System.out.println("URI: " + uri.toString());
            System.out.println("Scheme: " + uri.getScheme());
            System.out.println("Host: " + uri.getHost());
            System.out.println("Path: " + uri.getPath());
            System.out.println("Query: " + uri.getQuery());
            System.out.println("Fragment: " + uri.getFragment());
            
            // Check URI properties
            System.out.println("Is Absolute: " + uri.isAbsolute());
            System.out.println("Is Opaque: " + uri.isOpaque());
            
            // Convert URI to URL
            URL url = uri.toURL();
            System.out.println("Converted to URL: " + url);
            
            // Create relative URI
            URI relativeURI = new URI("/api/posts");
            URI resolvedURI = uri.resolve(relativeURI);
            System.out.println("Resolved URI: " + resolvedURI);
            
        } catch (URISyntaxException | MalformedURLException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

🔹 Reading Content from URL

Download content directly from a URL:

import java.net.*;
import java.io.*;

public class URLContentReader {
    public static void main(String[] args) {
        try {
            // Create URL
            URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
            
            // Open input stream
            InputStream inputStream = url.openStream();
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream));
            
            // Read content
            String line;
            StringBuilder content = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            
            // Close streams
            reader.close();
            inputStream.close();
            
            // Print content
            System.out.println("Content from URL:");
            System.out.println(content.toString());
            
        } catch (IOException e) {
            System.out.println("Error reading URL: " + e.getMessage());
        }
    }
}

🔹 URL Connection Details

Get detailed information about URL connections:

import java.net.*;
import java.io.*;
import java.util.Map;

public class URLConnectionInfo {
    public static void main(String[] args) {
        try {
            // Create URL and open connection
            URL url = new URL("https://www.google.com");
            URLConnection connection = url.openConnection();
            
            // Connect to get headers
            connection.connect();
            
            // Get connection information
            System.out.println("URL: " + connection.getURL());
            System.out.println("Content Type: " + connection.getContentType());
            System.out.println("Content Length: " + connection.getContentLength());
            System.out.println("Last Modified: " + connection.getLastModified());
            System.out.println("Expiration: " + connection.getExpiration());
            
            // Get all headers
            System.out.println("\nAll Headers:");
            Map> headers = connection.getHeaderFields();
            for (String key : headers.keySet()) {
                System.out.println(key + ": " + headers.get(key));
            }
            
            // Check if we can read/write
            System.out.println("\nConnection Properties:");
            System.out.println("Do Input: " + connection.getDoInput());
            System.out.println("Do Output: " + connection.getDoOutput());
            System.out.println("Use Caches: " + connection.getUseCaches());
            
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

🔹 URL vs URI Comparison

Understanding the differences between URL and URI:

URL (Uniform Resource Locator):

  • Purpose: Locate and access web resources
  • Connection: Can open connections to resources
  • Methods: openStream(), openConnection()
  • Example: https://www.example.com/page.html
  • Use case: When you need to actually connect to resource

URI (Uniform Resource Identifier):

  • Purpose: Identify resources (may not be accessible)
  • Connection: Cannot directly open connections
  • Methods: resolve(), relativize(), normalize()
  • Example: urn:isbn:1234567890
  • Use case: When you need to manipulate or identify resources

🔹 URL Encoding/Decoding

Handle special characters in URLs:

import java.net.*;
import java.io.UnsupportedEncodingException;

public class URLEncoding {
    public static void main(String[] args) {
        try {
            // Original string with special characters
            String originalString = "Hello World! How are you?";
            System.out.println("Original: " + originalString);
            
            // Encode URL
            String encodedString = URLEncoder.encode(originalString, "UTF-8");
            System.out.println("Encoded: " + encodedString);
            
            // Decode URL
            String decodedString = URLDecoder.decode(encodedString, "UTF-8");
            System.out.println("Decoded: " + decodedString);
            
            // Build URL with parameters
            String baseUrl = "https://api.example.com/search";
            String query = "Java Programming";
            String category = "tutorials & guides";
            
            String fullUrl = baseUrl + "?q=" + URLEncoder.encode(query, "UTF-8") 
                + "&category=" + URLEncoder.encode(category, "UTF-8");
            
            System.out.println("Full URL: " + fullUrl);
            
        } catch (UnsupportedEncodingException e) {
            System.out.println("Encoding error: " + e.getMessage());
        }
    }
}

Output:

Original: Hello World! How are you?

Encoded: Hello+World%21+How+are+you%3F

Decoded: Hello World! How are you?

🧠 Test Your Knowledge

Which class can open a connection to a web resource?