在Perl中发出HTTP GET请求的最简单方法是什么?
时间:2020-03-06 14:44:15 来源:igfitidea点击:
我有一些用PHP编写的代码,用于使用我们的简单Web服务,我也想在Perl中为可能喜欢该语言的用户提供这些代码。发出HTTP请求的最简单方法是什么?在PHP中,我可以使用file_get_contents()在一行中完成此操作。
这是我想移植到Perl的全部代码:
/**
* Makes a remote call to the our API, and returns the response
* @param cmd {string} - command string ID
* @param argsArray {array} - associative array of argument names and argument values
* @return {array} - array of responses
*/
function callAPI( $cmd, $argsArray=array() )
{
$apikey="MY_API_KEY";
$secret="MY_SECRET";
$apiurl="https://foobar.com/api";
// timestamp this API was submitted (for security reasons)
$epoch_time=time();
//--- assemble argument array into string
$query = "cmd=" .$cmd;
foreach ($argsArray as $argName => $argValue) {
$query .= "&" . $argName . "=" . urlencode($argValue);
}
$query .= "&key=". $apikey . "&time=" . $epoch_time;
//--- make md5 hash of the query + secret string
$md5 = md5($query . $secret);
$url = $apiurl . "?" . $query . "&md5=" . $md5;
//--- make simple HTTP GET request, put the server response into $response
$response = file_get_contents($url);
//--- convert "|" (pipe) delimited string to array
$responseArray = explode("|", $response);
return $responseArray;
}
解决方案
看一下LWP :: Simple。
对于更多涉及的查询,甚至有一本关于它的书。
LWP ::简单:
use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
我将使用LWP :: Simple模块。
尝试使用HTTP :: Request模块。
此类的实例通常传递到LWP :: UserAgent对象的request()方法。
LWP :: Simple具有我们要寻找的功能。
use LWP::Simple; $content = get($url); die "Can't GET $url" if (! defined $content);

