import java.net.URL; import java.net.HttpURLConnection; import java.io.InputStreamReader; import java.io.BufferedReader; /** * This program inputs a URL from the user and outputs the * HTTP response received by sending a GET request to the * specified Web server. */ public class WebBrowserA { public static void main(String args[]) { try { // Connect to the server specified by the user System.out.print("Please enter a URL: "); BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in)); String url = userIn.readLine(); HttpURLConnection connection = (HttpURLConnection)(new URL(url).openConnection()); // Send the HTTP request to the server and receive back // the response connection.connect(); // Output the HTTP response: System.out.println("Server response: "); // 1. The status line (this may not work on all systems; // if not, use getResponseCode() and getResponseMethod() // instead) System.out.println(connection.getHeaderField(0)); // 2. The header fields String key; for (int i=1; (key=connection.getHeaderFieldKey(i))!=null; i++) { System.out.println(key + ": " + connection.getHeaderField(i)); } // 3. A blank line System.out.println(); // 4. The body of the response BufferedReader serverIn = null; try { serverIn = new BufferedReader( new InputStreamReader(connection.getInputStream())); } // Must use error stream if 404 returned catch (java.io.FileNotFoundException fnf) { serverIn = new BufferedReader( new InputStreamReader(connection.getErrorStream())); } String aLine; while ((aLine = serverIn.readLine()) != null) { System.out.println(aLine); } } catch (Exception e) { e.printStackTrace(); } return; } }