Thursday, May 07, 2009

Make an HTTP Request to an Address Protected by HTTP Basic Authentication

There are a number of tutorials using LWP and credentials, but none of those worked for me-- additionally I had no idea what the realm was (the server never sent it!).

It's possible to modify the request using authorization_basic which does not require a realm. This is what I used successfully.

Fiddler2, which can sniff packets from IE or Google Chrome, was invaluable here.

This is the code:

use HTTP::Request::Common;
use HTTP::Headers;
use LWP::UserAgent;
use LWP::Debug qw(+); #get the most logging available
my $username = 'usernamehere';
my $password = 'passwordhere';
my $host = 'blah.blha.com';
my %cookies = ();

my $path = '/path/to/your/page';

printf("Creating User Agent\n");
my $browser = LWP::UserAgent->new;
$browser->cookie_jar( {} );

printf("Creating Request\n");
my $request = HTTP::Request->new(GET => '$host$path');
printf("Add auth data\n");
$request->authorization_basic($username, $password);

printf("Sending Request\n");
my $response = $browser->request($request);

die "Error: ", $response->header('WWW-Authenticate') ||
'Error accessing',
# ('WWW-Authenticate' is the realm-name)
"\n ", $response->status_line, "\n at $url\n Aborting"
unless $response->is_success;


One other note. The syntax for the other types of requests can get a bid unwieldy. A list of key=value pairs is straightforward:

$ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]);


But what about sending XML? I created the following if statement for a request wrapper.

  if($method eq 'GET') {
$request = HTTP::Request->new(GET => $url);
} else {
$request = HTTP::Request->new($method => $url);
$request->content_type( 'application/xml' );
$request->content( $body );
}

No comments:

Labels

Blog Archive

Contributors