How to handle HTTP Post Errors - perl

An error displays when I run my Perl script. It says, Internal Server Error. Error Code 500. How can I handle this?
use warnings;
use strict;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $url = "https://myhost/test/server.php";
my $req = HTTP::Request->new(POST => $url);
$req->header('content-type' => 'application/json');
my $post_data = {"value": "sample", "value2":"sample2"};
$req->content($post_data);
#print $req->as_string;
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "Received reply: $message\n";
}
else {
print "HTTP POST error code: ", $resp->code, "\n";
print "HTTP POST error message: ", $resp->message, "\n";
}

This is not valid perl:
my $post_data = {"value": "sample", "value2":"sample2"};
You need to enclose your the value in single quotes:
my $post_data = '{"value": "sample", "value2":"sample2"}';
Alternatively, you can start with a perl hash, and build the json string using JSON:
use JSON;
my %hash = ( value => 'sample', value2 => 'sample2' );
my $post_data = to_json( \%hash );

Related

Perl Why doesn't POST work when the variable is set by <> rather than directly assigned?

When I directly assign a name to the variable $connection_name, this script works, but I would like to take a user input and assign that to the variable. When I do that, it doesn't work. I get an error 400 bad request.
#!/usr/bin/perl
use strict;
use warnings;
use LWP;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "XXXX"
# Get name for connection
print "Connection Name?";
my $connection_name= <>;
print $connection_name;
# HTTP request header fields
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/json');
# POST data in the HTTP request body
my $post_data = "{
\"name\":\"$connection_name\",
\"origin_country\":\"us\",
\"datasource_type\":\"cfdcb449-1204-44ba-baa6-9a8a878e6aa7\"
}"
$req->content($post_data);
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "Received reply: $message\n";
}
else {
print "HTTP POST error code: ", $resp->code, "\n";
print "HTTP POST error message: ", $resp->message, "\n";
}
When you hardcoded $connection_name, you probably didn't include a line feed as you do now. Add
chomp($connection_name);
And please use a proper JSON generator.
use JSON::XS qw( encode_json );
my $post_data = encode_json({
name => $connection_name,
origin_country => "us",
datasource_type => "cfdcb449-1204-44ba-baa6-9a8a878e6aa7",
});

Print http request response in JSON format

#!/usr/bin/perl
use strict;
use warnings;
use JSON qw(decode_json);
use JSON;
use LWP::UserAgent;
use HTTP::Request;
#GET_METHOD
my $usagnt_get = LWP::UserAgent->new;
my $server_end_point_get = "http://192.168.201.1:8000/c/r";
my $reqst_get = HTTP::Request->new( GET => $server_endpoint_get );
$reqst_get->header( 'content-type' => 'application/json' );
#Request User Agent
my $respnse_get = $usagnt->request( $reqst_get );
if ( $resp_get->is_success ) {
my $message = $respnse_get->decoded_content;
print "\n Received GET Response:\n$res_message\n";
print "\n****** GET operations SUCCESS..!\n";
}
else {
print "HTTP_GET error code:", $respnse_get->code, "\n";
print "HTTP_GET error message:", $respnse_get->res_message, "\n";
}
Please help me to get output with JSON format of ie requesting method with HTTP req and get method is capturing with all the projects list in getting method.
# Here is the successfully compiled code
!/usr/bin/perl
use strict;
use LWP::UserAgent;
my $token="";
my $uri = 'http://xxx.xxx.xxx.xxx:8000/a/b';
my $json => '{"username":"user","password":"pwd"}';
my $req = HTTP::Request->new('POST', $uri );
$request->header( 'Content-Type' => 'application/json');
$request->content( $json );
my $lwp = LWP::UserAgent->new;
my $message = $lwp->request( $request );
if ( $message->is_success ) {
my $token= $message->content;
print "\n Received POST Response:\n$token\n";
} else {
print "error code:", $message->code,"\n";
print "error message:", $message->as_string(), "\n";
}

Where can I find the request body in HTTP::Server::Simple

I have the following simple server:
And I am trying to locate where the request body (or content) is.
I have tried dumping $self and $cgi but they didn't contain the field (I am asuming because they don't carry any information regarding the request)
How can I get the request body ?
package MyWebServer;
use strict;
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);
use Data::Dumper;
my %dispatch = (
'/hello' => \&resp_hello,
# ...
);
sub handle_request {
my $self = shift;
my $cgi = shift;
my $path = $cgi->path_info();
my $handler = $dispatch{$path};
print "printing self in request".Dumper($cgi);
my $req = $cgi->get_request;
if (ref($handler) eq "CODE") {
print "HTTP/1.0 200 OK\r\n";
$handler->($cgi, "asd");
} else {
print "HTTP/1.0 404 Not found\r\n";
print $cgi->header,
$cgi->start_html('Not found'),
$cgi->h1('Not found'),
$cgi->end_html;
}
}
sub resp_hello($$) {
my ($cgi, $asd) = #_; # CGI.pm object
my $who = $cgi->param('name');
print $cgi->header,
$cgi->start_html("Hello"),
$cgi->h1("Hello world!!"),
$cgi->h2("Azdh $asd");
$cgi->end_html;
}
# start the server on port 8080
my $pid = MyWebServer->new(8081)->background();
print "Use 'kill $pid' to stop server.\n";
EDIT: Here is an example request:
use strict;
require LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(GET => "http://localhost:8081/hello");
$req->content("<foo>3.14</foo>"); # the request body
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "Received reply: $message\n";
}
else {
print "HTTP GET error code: ", $resp->code, "\n";
print "HTTP GET error message: ", $resp->message, "\n";
}
It's a bit old, but facing the same issue, here's the solution :
$cgi->param('POSTDATA');
That's all you need to retreive the Body contents.
cheers.
The request object you obtained using the line $req = $cgi->get_request is a CGI::Request object. Since this is a request object, it will have only attributes (parameters passed on to the request). Please note that only response objects will have content. So, to see all the parameters you have passed, you can use the as_string() object method as mentioned below.
print $req->as_string;
For more information about accessing individual parameters of the request object, please see CGI::Request documentation in http://search.cpan.org/~mrjc/cvswebedit-v2.0b1/cvs-web/lib/CGI/Request.pm.

Invalid request parameter in Paypal API

Hi I just picked up the code sample for perl and tried to do a payment to my sandbox developer test account with the following
sub promote {
my $headers = HTTP::Headers->new(
'X-PAYPAL-SECURITY-USERID'=> 'alexjaquet-facilitator_api1.gmail.com',
'X-PAYPAL-SECURITY-PASSWORD' => 'xxxxx',
'X-PAYPAL-SECURITY-SIGNATURE' => 'An5ns1Kso7MWUdW4ErQKJJJ4qi4-
3fjxb5G1RfUPmQ5kIdwdsH7znTJ',
'X-PAYPAL-SERVICE-VERSION' => '1.1.0',
'X-PAYPAL-APPLICATION-ID' => 'APP-80W284485P519543T',
'X-PAYPAL-REQUEST-DATA-FORMAT' => 'NV',
'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'NV');
my $content = sprintf("%s&%s&%s&%s&%s&%s&%s&%s&%s&%s&%s&%s&%s&%s&%s",
'senderEmail=alexjaquet-facilitator#gmail.com',
'actionType=PAY',
'currencyCode=USD',
'feesPayer=EACHRECEIVER',
'receiverList.receiver(0).email=alexjaquet-facilitator#gmail.com ',
'receiverList.receiver(0).primary=false',
'receiverList.receiver(0).amount=20.00',
'returnUrl=http:myreturnurl',
'cancelUrl=http:mycancelurl',
'requestEnvelope.errorLanguage=en_US',
'clientDetails.ipAddress=127.0.0.1',
'clientDetails.deviceId=mydevice',
'clientDetails.applicationId=PayNvpDemo');
my $req = HTTP::Request->new($method,'https://svcs.sandbox.paypal.com/AdaptivePayments
/Pay',$headers, $content);
my $ua = LWP::UserAgent->new;
my $res = $ua->request($req);
if ($res->is_success) {
print "Content-Type: text/html\n\n";
print $res->content;}
else {
print "Content-Type: text/html\n\n";
print $res->status_line, "\n";}
}
but the response I get he's the following :
error(0).domain=PLATFORM&error(0).subdomain=Application&error(0).severity=Error&error(0).category=Application&error(0).message=Invalid+request+parameter%3A+email+alexjaquet-facilitator%40gmail.com++is+invalid&error(0).parameter(0)=email&error(0).parameter(1)=alexjaquet-facilitator%40gmail.com+

how to post an url and to retrive the website contents using perl

I want to get a solution for how to post one particular url and to retrieve the content. Is it possible with perl ? let it be a website where we are searching for one particular id, and we are supposed to get the associated information tagged to that id.
Use this
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "";
# set custom HTTP request header fields
my $req = HTTP::Request->new(GET => $server_endpoint);
$req->header('content-type' => 'application/json');
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "Received reply: $message\n";
}
else {
print "HTTP GET error code: ", $resp->code, "\n";
print "HTTP GET error message: ", $resp->message, "\n";
}
Or you can do this way also usingLWP::Simple
use strict;
use warnings;
use LWP::Simple;
my $url = 'http://www.example.com';
my $content = get $url or die "Unable to get $url\n";
print $content;