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.
我正在尝试从变量中以json格式的$url
捕获响应,然后使用JSON的decode_json
方法将其转换为哈希结构以获取国家/地区代码。但我无法在变量中获得响应。
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
答案 0 :(得分:2)
WWW::Curl文档中的第一个示例代码块对此进行了解释。我在这里将其与问题中的代码一起复制。
my $curl = WWW::Curl::Easy->new;
$curl->setopt(CURLOPT_URL,$url);
# A filehandle, reference to a scalar or reference to a typeglob can be used here.
my $response_body;
$curl->setopt(CURLOPT_WRITEDATA,\$response_body);
# Starts the actual request
my $retcode = $curl->perform;
my %hash = decode_json($response_body);
$country = $hash->{body}->{country};
您需要将某种引用设置为CURLOPT_WRITEDATA
选项。我们使用了标量引用,变量$response_body
将在$curl->perform
完成后包含响应主体。然后,您可以解码JSON。
答案 1 :(得分:0)
经过多次与WWW :: Curl :: Easy拒绝打印到变量的问题挣扎,并不断写入STDOUT,我终于找到了问题!
你想从 WWW-Curl-4.17 获取你的WWW :: Curl :: Easy,而在WWW-Curl-3.02中找到WWW :: Curl :: Easy 强>
所以只需用整个WWW-Curl 4.17软件包覆盖以前的WWW :: Curl :: Easy安装:
http://search.cpan.org/~szbalint/WWW-Curl-4.17/lib/WWW/Curl.pm
然后它将服从CURLOPT_WRITEDATA。 事实上,其他Curl甚至不知道CURLOPT_WRITEDATA,因为您将通过添加 use strict 来实现;
答案 2 :(得分:-1)
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);