--#--
Baby gets his teeth
--#--
So far baby Pete posts, but when the remote site responds, he doesn't
do a thing with the data. So, let's teach Pete to eat:
byte[] mouthful = new byte[4096];
int eaten;
while(eaten = response.read(mouthful)) !=-1)
System.out.write(mouthful, 0, eaten);
System.out.println();
socket.close();
That was a little too cute, so let's get serious for minute. Code that
opens sockets and writes and reads on them can get into all sorts of
trouble -- maybe the remote site isn't even there, maybe there's a network
problem ... Who know? Anyway, this code could throw several possible Java IO
and network exceptions. But this isn't serious code, so we don't need
anything more than trivial exception handling, which we'll implement with
a single try ... catch block.
try {
(our code goes here)
}
catch (Exception e) {
System.out.println("What went wrong? " + e.getMessage());
}
One last touch (for now), for our own convenience. Let's construct the
post ahead of time so the Java engine will count its content length for
us. For clarity, I'll repeat the whole block of code that writes to the socket.
String request =
"query=java&form=search&resultdocs=30&srcmags=checked&srcbooks=checked";
try {
Socket socket = new Socket("people.yahoo.com", 80);
InputStream response = socket.getInputStream();
PrintWriter agent =
new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
agent.println("POST /py/psAdvSearch.py HTTP/1.0");
agent.println("Content-type: application/x-www-form-urlencoded");
agent.println("Content-length: " + request.length()); // work for us!
agent.println();
agent.println(request);
agent.flush();
All you need is to wrap all this in a class definition and a "main" method,
and baby Pete in
his first incarnation is ready to go to town.