Chapter 4: The Socket Library- P2
Now we wait for a response from the server. We read in the response and
selectively echo it out, where we look at the $response, $header, and $data
variables to see if the user is interested in looking at each part of the reply:
# get the HTTP response line
my $the_response=<F>;
print $the_response if ($all || defined
$response);
# get the header data
while(<F>=~ m/^(\S+):\s+(.+)/) {
print "$1: $2\n" if ($all || defined $header);
}
# get the entity body
if ($all || defined $data) {
print while (<F>);
}
The full source code looks like this:
#!/usr/local/bin/perl -w
# socket based hypertext version of UNIX cat use strict;
use Socket; # include Socket
module
require 'tcp.pl'; # file with Open_TCP
routine
require 'web.pl'; # file with parseURL
usage information sub help {
print "Hypertext cat help\n\n";
print "This program prints out documents on a
remote web server.\n";
print "By default, the response code, header, and
data are printed\n";
print "but can be selectively printed with the -
r, -H, and -d options.\n\n";
usage();
} # Given a URL, print out the data there sub hcat {
# grab paramaters
my ($full_url, $response, $header, $data)=@_;
# assume that response, header, and data will be
printed
my $all = !($response || $header || $data);
# if the URL isn't a full URL, assume that it is
a http request
my $the_response=<F>;
print $the_response if ($all || defined
$response);
# get the header data
while(<F>=~ m/^(\S+):\s+(.+)/) {
print "$1: $2\n" if ($all || defined $header);
}
# get the entity body
if ($all || defined $data) {
print while (<F>);
}
# close the network connection
close(F);
}
Shell Hypertext cat
With hcat, one can easily retrieve documents from remote web servers. But
there are times when a client request needs to be more complex than hcat is
willing to allow. To give the user more flexibility in sending client requests,
we'll change hcat into shcat, a shell utility that accepts methods, headers, and
entity-body data from standard input. With this program, you can write shell
scripts that specify different methods, custom headers, and submit form data.
All of this can be done by changing a few lines around. In hcat, where you
see this:
# request the path of the document to get
print F "GET $the_url[3] HTTP/1.0\n";
print F "Accept: */*\n";