How to POST content with an HTTP Request (Perl) - perl

use LWP::UserAgent;
use Data::Dumper;
my $ua = new LWP::UserAgent;
$ua->agent("AgentName/0.1 " . $ua->agent);
my $req = new HTTP::Request POST => 'http://example.com';
$req->content('port=8', 'target=64'); #problem
my $res = $ua->request($req);
print Dumper($res->content);
How can I send multiple pieces of content using $req->content? What kind of data does $req->content expect?
It only sends the last one.
Edit:
Found out if i format it like 'port=8&target=64' it works. Is there a better way?

my $ua = LWP::UserAgent->new();
my $request = POST( $url, [ 'port' => 8, 'target' => 64 ] );
my $content = $ua->request($request)->as_string();

The answer given didn't work for me. I still had the same problem as OP.
The documentation for LWP::UserAgent wants a hash or array reference.
This works:
my $url = 'https://www.google.com/recaptcha/api/siteverify';
my $ua = LWP::UserAgent->new();
my %form;
$form{'secret'}='xxxxxxxxxxxxxxxxxxxxxxx';
$form{'response'}=$captchaResponse;
my $response = $ua->post( $url, \%form );
my $content = $response->as_string();

Using together LWP::UserAgent and HTTP::Request as it is also quite common if not even more frequent practice , I was little puzzled that the standard POST and GET / request were almost not discussed at SO aside from json as them are in vast majority used.
POST
my $ua = LWP::UserAgent->new();
my $req = new HTTP::Request(
'POST' => "http://url/path",
['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'],
'par1=par1value&par2=par2value'
);
$ua->request($req);
similarly for the GET
my $ua = LWP::UserAgent->new();
my $req = new HTTP::Request(
'GET' => "http://url/path",
['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'],
'par1=par1value&par2=par2value' # or I presume attaching the query string directly to the url
);
$ua->request($req);
another format form , where the first two parameters (method and url) are not fused into a one, not like the previous, but separately
my $request = HTTP::Request->new( 'POST', $url, [ parameter1 => 'parameter1Value' ] );
request->header( 'Content-Type' => 'application/json' )
There is a similar question, but just regards LWP and Json, but it could be probably accomplished only by using both LWP and HTTP::Request together as suggested by that question chosen answer, and the POST and GET were missing there but it might not have been obvious
How can I make a JSON POST request with LWP?
Note:
I post this specially also, since the concrete/concise usage for POST/GET is not mentioned even in the documentation
https://metacpan.org/pod/HTTP::Request

Related

how to send a http patch request with Lwp::Useragent?

I am working against the salesforce rest api with lwp::useragent.
I have to use the http patch request.
For get and post requests we get use the following code:
require LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->env_proxy;
my $get_response = $ua->get('http://search.cpan.org/',x=>'y');
my $post_response = $ua->post('http://search.cpan.org/',x=>'y');
Unfortunately this does not work
my $patch_response = $ua->patch('http://search.cpan.org/',x=>'y');
I don't find how to do it with this module.
There is a workaround to this problem like explained here How do I send a request using the PATCH method for a Salesforce update?
This works but this is not a nice solution.
I saw that with python it is possible to make explicitly patch requests How do I make a PATCH request in Python? so i assume that there is also an option with perl.
my $request = HTTP::Request->new(PATCH => $url);
... Add any necessary headers and body ...
my $response = $ua->request($request);
This has recently got a whole lot easier. PATCH is now implemented (like POST) in HTTP::Message.
First, update the HTTP::Message module (to 6.13 or later).
Then
my %fields = ( title => 'something', body => something else');
my $ua = LWP::UserAgent->new();
my $request = HTTP::Request::Common::PATCH( $url, [ %fields ] );
my $response = $ua->request($request);

Perl HTTP POST request with Content type and Authorization token

I need to send an HTTP POST request with the following HTTP headers:
Content-type: 'application/atom+xml'
Authorization: MyLogin auth=$token
The token is coming from an authorization subroutine. Here is the Perl making the actual request after the subroutine is successful:
my $ua = LWP::UserAgent->new;
my $req = $ua->post ( $url );
$req = header('Content-type' => 'application/atom+xml');
$req = header('Authorization' => "MyLogin auth=$token");
However, I receive the following error when run:
Undefined subroutine &main::header called ...
How can I accomplish this?
According to the LWP::UserAgent documentation, you can set additional headers by passing them as arguments to post:
my $ua = LWP::UserAgent->new;
my $response = $ua->post($url,
'Content-type' => 'application/atom+xml',
'Authorization' => "MyLogin auth=$token"
);
Note that $ua->post actually sends the request, so trying to set the headers after calling it, as you do in your example code, is useless. (Not to mention the fact that there is no header function in the main namespace unless you import it from somewhere or write it yourself.)

Posting to a WEB API from Perl results in a null value in [FromBody]

We have created a WEB API (in .NET framework 4.0) and gave the endpoint info to one of our clients. They created a program in Perl that posts to our endpoint.
Every post they have made so far arrives into our endpoint as null. When we initially started programming, we had that same issue in JQuery when posting by means of $.ajax. We solved it by adding a '=' at the beginning of the post data.
The Perl code they have submitted is the following:
sub _postPackages {
my ($self,$dataToSend) = #_;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("integrationapp/1.0 ");
# Create a request
my $req = HTTP::Request->new(POST => $self->{postAddress} );
$req->content_type("application/json;charset=utf-8");
$req->content($dataToSend->{data});
#print Data::Dumper->Dump([$req]);
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
where postAddress is our endpoint and $dataToSend is the message data. Is it possible that they need to add the '=' at the beginning of the $dataToSend message.
Any help will be greatly appreciated.
This is a bit of pseudo code here..
But I'm guessing you want to do something like this:
# some post sub
my ($self, $data) = #_;
my $ua = $self->get_user_agent();
my $json_xs = $self->get_json_xs();
my $json_encoded = $json_xs->utf8->encode($data);
$self->set_post_data($json_encoded);
$self->set_api_call();
my $response_body = $ua->post(
$self->get_api_call(),
'Content' => $self->get_post_data(),
'Content-type' => "application/json;charset=UTF-8"
);
print STDERR "POSTING NEW RESOURCE: " . Dumper($self);

download file after perl post

This request returns a file of type ZIP how can I retrieve that file from that request?
# put timeouts, proxy etc into the useragent if needed
my $ua = LWP::UserAgent->new();
my $req = POST $in_u, Content_Type => 'form-data', Content => $in_r;
my $response = $ua->request($req);
if ($response->is_success())
{
print $response->content;
}
I think you can use the content method on your $req object to get the raw content returned as a result of the POST. If the content is huge, then content_ref method is more suitable and offers to directly manipulate the content.
my $zfile = $req->content;
and crack on $zfile with Archive::Zip as DVK suggested.
You can use Archive::Zip CPAN module

Can I pass GET string in UserAgent post method

I call in this mode:
my $ua = new LWP::UserAgent;
my $response= $ua->post('www.example.com', {param1=>'val1',param2=>'val2'...} );
Can I call the above in the same way passing the values in GET form?:
my $response= $ua->post('www.example.com?param=val1&param2=val2' );
It is because I'm using Firebug and when I go to Net tab under the "POST" tab it shows individual parameters as well as a GET string for POST submitted requests.
So I was wondering if I use GET string in this function call.
Parametersapplication/x-www-form-urlencoded
Itemid 4 option com_search
searchword dsd task search Source
Content-Type:
application/x-www-form-urlencoded
Content-Length: 53
searchword=dsd&task=search&option=com_search&Itemid=4
In short you can pass GET strings yes, but if your end code does not accept GET METHOD it will fail.
Also you might still need to specify some parameters since the post method asks for post(url,array_with_parameters).
sub post {
require HTTP::Request::Common;
my($self, #parameters) = #_;
my #suff = $self->_process_colonic_headers(\#parameters, (ref($parameters[1]) ? 2 : 1));
return $self->request( HTTP::Request::Common::POST( #parameters ), #suff );
}
Using along with HTTP::Request you can specify it at the content in the way you prefer:
# Create a user agent object
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1 ");
# Create a request
my $req = HTTP::Request->new(POST => 'http://www.example.com');
$req->content_type('application/x-www-form-urlencoded');
$req->content('searchword=dsd&task=search&option=com_search&Itemid=4');
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success) {
print $res->content;
} else {
print $res->status_line, "\n";
}
Read more...