|
HTTP for Text Transport
An Introduction with Examples in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
package internet;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* A class that retrieves text files over the Internet
* using HTTP.
*
* @version 1.0
* @author Prof. David Bernstein, James Madison University
*/
public class HTTPFileRetriever
{
private List<String> lines;
/**
* Explicit Value Constructor
*
* @param url The URL of the file (including protocol)
*/
public HTTPFileRetriever(String url)
{
BufferedReader in;
String line;
URL u;
try
{
u = new URL(url);
in = new BufferedReader(
new InputStreamReader(
u.openStream()));
lines = new LinkedList<String>();
while ( (line=in.readLine()) != null)
{
try
{
lines.add(URLDecoder.decode(line, "UTF-8"));
}
catch (Exception de)
{
// Ignore it
}
}
in.close();
}
catch (MalformedURLException mue)
{
// Do nothing
System.err.println(mue);
}
catch (IOException ioe)
{
// Do nothing
System.err.println(ioe);
}
}
/**
* Get the lines in the file.
*
* @return The linesi in the file
*/
public List<String> get()
{
return lines;
}
}
connect():
connect():
getHeaderField(String name) returns a
String containing the valuegetHeaderFields() returns a
Map<String,List<String>>
getContent() gets the content (as an
Object) based on the content typegetInputStream() gets the InputStream
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.");
}
}
}