LWP::UserAgent using we are sending request to an endpoint which is sending the response as HTTP/1.1 200 OK or HTTP/1.1 200 200. I used pattern match to check the response the status.
But I was thinking to use some common function from which we can check the status of response instead of having pattern match in the HTTP STATUS. Below is the code which I have .
use LWP::UserAgent;
my $ua = LWP::UserAgent->new( );
$ua->timeout(30);
my $req = HTTP::Request->new(POST => "$EndPoint");
$req->content_type('text/xml');
$req->content($send_data);
my $response = $ua->request($req);
my $http_status = '';
if ( $response =~ m/^HTTP.*?\s(.*)/ ) {
$http_status = uc($1); # It is probably already upper case -- just making sure.
}
if ( $http_status =~ m/200/ ) {
if ( $response =~ m/Status=\"Successful\"/ ) {
print "Successful\n";
} else {
my $error_code = '';
if ( $response =~ m/Error Code=\"(. ?)\"/ ) {
print "Error: $1 \n";
}
}
I tried to use below code to check the status but I am getting error Can't locate object method "is_success" via package "HTTP/1.1 200 OK
if($response->is_success){
print Dumper($response);
} else {
print Dumper($response->status_line);
}
Edit
perl send_request.pl
Can't locate object method "is_success" via package "HTTP/1.1 200 OK
##I added a print on $response
Connection: close
Date: Mon, 10 Jan 2022 17:36:58 GMT
Accept: text/xml, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Server: Apache
Vary: Accept-Encoding
Content-Length: 356
Content-Type: text/xml;charset=utf-8
Client-Date: Mon, 10 Jan 2022 17:36:58 GMT
Client-Peer: XXXXX
Client-Response-Num: 1
SOAPAction: ""
CodePudding user response:
There are methods to query the response, you rarely ever need to parse its message.
A LWP::UserAgent::get returns an HTTP::Response object. In its documentation we find
is_success, is_info, is_error, is_client_error, is_server_error, is_redirect
The most commonly used is is_success, with an example right in the synopsis.
More details on what exactly these mean are in HTTP::Status
CodePudding user response:
To check for a 2xx code:
if ( $response->is_success ) { ... }
To check for 200 specifically (in the rare event you want to distinguish 200 OK from 201 Created),
if ( $response->code == 200 ) { ... }
If you want the string that follows, you can use
$response->status_line # "200 OK" or "200 200"
