I tried to use HTTP::Request::Common
to do a post to a URL. Unfortunately, it doesn't seem to work with authentication, and I had to switch back to plain ol' HTTP::Request
. If I didn't need the authentication, I could have done the whole thing this way:
use HTTP::Request::Common;
my $browser = LWP::UserAgent->new;
$browser->request (
POST $url,
Content => [
Name => $name,
Address => $address,
],
);
Unfortunately, because of authentication, I had to fall back to HTTP::Request
:
use HTTP::Request;
my $browser = LWP::UserAgent->new;
my $request = HTTP::Request;
my $request->authentication_basic($user, $pass);
my $request->method("POST");
my $request->url($url);
# Create Content Byte String
my $uri = URI->new('http://'); #URL isn't needed, just the object
$uri->form_query(Name => $name, Address => $address);
my $content = $uri->query;
$request->content($content);
# Set the headers for the content
$request->header( "Content-Type" => "application/x-www-form-urlencoded" );
$request->header( "Content-Length" => length($content) );
# Now send your request through your browser
my $response = $browser->request($request);
You can see the code is much more involved. I'd like to switch back to HTTP::Request::Common
because the code looks like it would be easier to maintain, but how do I handle authentication?
POST
is just a fancy constructor for a HTTP::Request
object. Use that to construct your request object, and then set authentication:
use HTTP::Request::Common;
my $browser = LWP::UserAgent->new;
my $request = POST $url,
Content => [
Name => $name,
Address => $address,
];
$request->authorization_basic($user, $pass);
my $response = $browser->request($request);