001package edu.pdx.cs410J.web; 002 003import java.io.*; 004import java.net.HttpURLConnection; 005import java.net.URL; 006import java.util.List; 007import java.util.Map; 008 009/** 010 * Demonstrates making an HTTP GET request using the {@link java.net.URLConnection} class 011 * 012 * @author David Whitlock 013 * @since Summer 2008 014 */ 015public class UrlHttpGet { 016 017 /** 018 * Fetches the content of a URL using an HTTP GET 019 * 020 * @param urlString The URL to GET 021 * @throws java.io.IOException If a problem occurs while reading URL 022 */ 023 private static void getURL(String urlString) throws IOException { 024 URL url = new URL(urlString); 025 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 026 conn.setRequestMethod("GET"); 027 conn.connect(); 028 029 PrintStream out = System.out; 030 out.println("Headers"); 031 032 Map<String,List<String>> headers = conn.getHeaderFields(); 033 for (String key : headers.keySet() ) { 034 out.print(" "); 035 if (key != null) { 036 out.print(key + ": "); 037 } 038 for (String value : headers.get(key)) { 039 out.print(value); 040 } 041 out.println("\n"); 042 } 043 044 out.println("\nContent"); 045 out.flush(); 046 047 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 048 do { 049 out.println(br.readLine()); 050 } while (br.ready()); 051 052 br.close(); 053 } 054 055 public static void main(String[] args) throws IOException { 056 String url = null; 057 058 for (String arg : args) { 059 if (url == null) { 060 url = arg; 061 062 } else { 063 usage("Extraneous command line argument: " + arg); 064 } 065 } 066 067 if (url == null) { 068 usage("Missing URL"); 069 } 070 071 getURL(url); 072 } 073 074 private static void usage(String message) { 075 PrintStream err = System.err; 076 err.println("** " + message); 077 err.println("usage: java UrlHttpGet url"); 078 System.exit(1); 079 } 080}