Kartik Parihar Kartik Parihar - 4 months ago 18
Perl Question

WWW::Curl::Easy output not capture

use JSON;
use WWW::Curl::Easy;

my $curl = WWW::Curl::Easy->new;
$curl->setopt(CURLOPT_NOBODY,1);
$curl->setopt(CURLOPT_TIMEOUT,3);
$curl->setopt(CURLOPT_VERBOSE,0);
$curl->setopt(CURLOPT_URL,$url);


my $response = (what to use here);

my %hash = decode_json($response);
$country = $hash->{body}->{country};
return $country;


#the output from url is in json format.
#but unable to capture that output in a response variable as object.


I am trying to capture reponse from
$url
which is in json format in variable then use JSON's
decode_json
method to convert that into hash structure to get country code. But I am not able to get the response in variable.

JSON Output:
{
"headers": {
"ipAddress": ["198.162.1.1"],
"type": ["PUBLIC_IP_ADDRESS"]
},
"body": {
"country": {
"isoCode": "CA",
"name": "Canada",
"geoNameId": 6251999
},
"continent": {
"name": "North America",
"code": "NA",
"geoNameId": 6255149
},
"city": {
"name": "Cranbrook",
"geoNameId": 5931800
},
"traits": {
"ipAddress": "198.162.1.1"
},
"location": {
"latitude": 49.4999,
"longitude": -115.7688,
"timeZone": "America/Edmonton"
},
"postal": {
"code": "V1C"
},
"subdivisions": [{
"name": "British Columbia",
"geoNameId": 5909050,
"isoCode": "BC"
}]
},
"statusCode": "OK"
}
200

Answer
This seems that WWW::Curl::Easy require file handle.
Look at bold lines


 #!/usr/bin/perl

 use WWW::Curl::Easy;
 use Data::Dumper ;

 my $resp_body ="";

 my $curl=WWW::Curl::Easy->new;

 $curl->setopt(CURLOPT_URL,$url);

# Define file handle and send it to string 
 open (my $fh, ">", \$resp_body);

$curl->setopt(CURLOPT_WRITEDATA,\$fh);

my $ret_code =$curl->perform;

if ($ret_code ==0){
 print "Response : $resp_body";
 }else{
 print "Error".$curl->errbuf ;
}
close($fh);
Comments