Sunday, September 14, 2008

LWP is Simple.

While I'm on the nerd tip, this is the simplest example I can get to grab the contents of a URL, with a optional username/password and/or proxy:

 
#!/usr/bin/perl

my $proxy = undef;
my $user = undef;
my $pass = undef;
my $url = 'http://localhost';

# Create a user agent object
require LWP::UserAgent;
my $ua = LWP::UserAgent->new;

if($proxy){
$ua->proxy(
['http', 'ftp'],
$proxy
);
}

# Create a request
my $req = HTTP::Request->new(
GET => $url
);
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
if(
defined($user) &&
defined($pass)
){
$res->authorization_basic(
$user,
$pass
);
}
# Check the outcome of the response
if ($res->is_success) {
return $res->content;
}
else {
warn $res->status_line;
return undef;
}
}



Wishing LWP::Simple would do this, but. Nope.

No comments: