AnyEvent-HTTP-ScopedClient
view release on metacpan or search on metacpan
lib/AnyEvent/HTTP/ScopedClient.pm view on Meta::CPAN
package AnyEvent::HTTP::ScopedClient;
{
$AnyEvent::HTTP::ScopedClient::VERSION = '0.0.5';
}
# ABSTRACT: L<AnyEvent> based L<https://github.com/technoweenie/node-scoped-http-client>
use Moose;
use namespace::autoclean;
use URI;
use Try::Tiny;
use MIME::Base64;
use HTTP::Request;
use Encode qw/encode_utf8/;
use AnyEvent::HTTP;
use URI::QueryParam;
use URI::Escape;
has 'options' => (
is => 'ro',
isa => 'HashRef',
);
sub request {
my ( $self, $method, $reqBody, $callback ) = @_;
if ( 'CODE' eq ref($reqBody) ) {
$callback = $reqBody;
undef $reqBody;
}
my %options = %{ $self->options };
try {
my %headers = %{ $options{headers} };
if ( 'HASH' eq ref($reqBody) ) {
my @pair;
# push @pair, "$_=$reqBody->{$_}" for ( keys %$reqBody );
push @pair, "$_=" . uri_escape_utf8( $reqBody->{$_} )
for ( keys %$reqBody );
$reqBody = join( '&', @pair );
}
my $sendingData
= ( $method =~ m/^P/ && $reqBody && length $reqBody > 0 ) ? 1 : 0;
$headers{'Content-Length'} = length $reqBody if $sendingData;
$headers{'Content-Type'} = 'application/x-www-form-urlencoded'
if ( $sendingData && !$headers{'Content-Type'} );
if ( $options{auth} ) {
$headers{Authorization}
= 'Basic ' . encode_base64( $options{auth}, '' );
}
if ( $ENV{DEBUG} ) {
print "$method " . $self->options->{url} . "\n";
while ( my ( $k, $v ) = each %headers ) {
print "$k: $v\n";
}
print "\n";
print "$reqBody\n" if $sendingData;
}
http_request(
$method,
$options{url},
headers => \%headers,
body => $sendingData ? encode_utf8($reqBody) : undef,
$callback
);
( run in 0.989 second using v1.01-cache-2.11-cpan-39bf76dae61 )