views:

5088

answers:

5

I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with file_get_contents().

Here's the entire code I want to port to 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;
}
+4  A: 

Take a look at LWP::Simple. For more involved queries, there's even a book about it.

bmdhacks
+21  A: 

LWP::Simple:

use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
kcrumley
so...we've got four responses mentioning LWP::Simple, I guess that's the one to use
davr
For static strings like 'http://URL', it's best to use single quotes to save perl the work of looking for things to interpolate.
AndrewJFord
For static strings, there's no _real_ overhead with double quotes. The reason to use single quotes is to make it clear to the next programmer that they don't need to look for interpolations in the code.
Dave Rolsky
+3  A: 

I would use the LWP::Simple module.

AndrewJFord
+1  A: 

Try the HTTP::Request module.

coppro
+6  A: 

LWP::Simple has the function you're looking for.

use LWP::Simple;
$content = get($url);
die "Can't GET $url" if (! defined $content);
Barry Brown