The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2002

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Urgent!

Posted by Eduardo on January 06, 2002 at 4:45 PM

Well... I have a problem in one assignment that I just don't know what to do. I hope there is an expert online, now... but... well, let's go:

I have to modify this HttpClient program to a better browser than a 1.0. As long as I undestood, it should be a couple of lines, only, but I didn't get it.

public class HttpClient {
public static void main(String[] args) {
try {
// Check the arguments
if ((args.length != 1) && (args.length != 2))
throw new IllegalArgumentException("Wrong number of args");

// Get an output stream to write the URL contents to
OutputStream to_file;
if (args.length == 2) to_file = new FileOutputStream(args[1]);
else to_file = System.out;

// Now use the URL class to parse the user-specified URL into
// its various parts.
URL url = new URL(args[0]);
String protocol = url.getProtocol();
if (!protocol.equals("http")) // Check that we support the protocol
throw new IllegalArgumentException("Must use 'http:' protocol");
String host = url.getHost();
int port = url.getPort();
if (port == -1) port = 80; // if no port, use the default HTTP port
String filename = url.getFile();

// Open a network socket connection to the specified host and port
Socket socket = new Socket(host, port);

// Get input and output streams for the socket
InputStream from_server = socket.getInputStream();
PrintWriter to_server = new PrintWriter(socket.getOutputStream());

// Send the HTTP GET command to the Web server, specifying the file
// This uses an old and very simple version of the HTTP protocol
to_server.print("GET " + filename + "\n\n");
to_server.flush(); // Send it right now!

// Now read the server's response, and write it to the file
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = from_server.read(buffer)) != -1)
to_file.write(buffer, 0, bytes_read);

// When the server closes the connection, we close our stuff
socket.close();
to_file.close();
}
catch (Exception e) { // Report any errors that arise
System.err.println(e);
System.err.println("Usage: java HttpClient []");
}
}
}



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us