The following example sends a request to an http server using a socket's output stream; then it reads the response using the socket's input stream. HTTP servers close the connection when they've sent the response.
import java.net.*;
import java.io.*;
public class Grabber {
public static void main(String[] args) {
int port = 80;
for (int i = 0; i < args.length; i++) {
try {
URL u = new URL(args[i]);
if (u.getPort() != -1) port = u.getPort();
if (!(u.getProtocol().equalsIgnoreCase("http"))) {
System.err.println("Sorry. I only understand http.");
continue;
}
Socket s = new Socket(u.getHost(), port);
OutputStream theOutput = s.getOutputStream();
// no auto-flushing
PrintWriter pw = new PrintWriter(theOutput, false);
// native line endings are uncertain so add them manually
pw.print("GET " + u.getFile() + " HTTP/1.0\r\n");
pw.print("Accept: text/plain, text/html, text/*\r\n");
pw.print("\r\n");
pw.flush();
InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
}
catch (MalformedURLException ex) {
System.err.println(args[i] + " is not a valid URL");
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
This is the beginning of a typical response:
utopia% java Grabber http://students.poly.edu:80 HTTP/1.0 200 OK Date: Thu, 17 Apr 1997 20:11:14 GMT Server: Apache/1.1.3 Content-type: text/html <title>Polytechnic University's Student Council Server</title> <body bgcolor="white" link=#0000dd vlink=#0000dd> <img src="http://www.poly.edu/images/poly_3d.jpeg" alt="">
How does this differ from essentially the same program we wrote a
little earlier that used URL
instead of sockets?