import java.io.*;
import java.net.*;
import java.util.*;

/**
 * An application that displays the headers in an
 * HTTP response.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class DisplayHeaders
{
    /**
     * The entry point of the application.
     *
     * @param args  The command line arguments (args[0] is the URL)
     */
    public static void main(String[] args)
    {
        Map<String, List<String>> headers;        
        Set<String>               names;        
        String                    arg;
        URL                       url;
        URLConnection             connection;
        
        
        if ((args != null) && (args.length > 0)) arg = args[0];
        else arg = "https://w3.cs.jmu.edu/bernstdh/web/cs462/index.php";
        
        try
        {
            url = new URL(arg);
            connection = url.openConnection();
            connection.connect();

            headers = connection.getHeaderFields();
            names = headers.keySet();
            for (String name: names)
            {
                System.out.println(name + ":");
                List<String> values = headers.get(name);
                for (String value: values)
                {
                    System.out.println("\t"+value);
                }
            }
        }
        catch (MalformedURLException mue)
        {
            System.out.println("Invalid URL: " + arg);
            
        }
        catch (IOException ioe)
        {
            System.out.println("Unable to connect.");            
        }
    }
}
