47

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;
}
user1614572
  • 153
  • 1
  • 7
davr
  • 18,877
  • 17
  • 76
  • 99

8 Answers8

80

LWP::Simple:

use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
Kevin
  • 5,874
  • 3
  • 28
  • 35
  • 1
    so...we've got four responses mentioning LWP::Simple, I guess that's the one to use – davr Sep 25 '08 at 18:03
  • 2
    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 Sep 25 '08 at 19:27
  • 10
    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 Sep 25 '08 at 19:31
20

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
  • 20,233
  • 15
  • 69
  • 105
6

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

bmdhacks
  • 15,841
  • 8
  • 34
  • 55
6

I would use the LWP::Simple module.

szabgab
  • 6,202
  • 11
  • 50
  • 64
AndrewJFord
  • 1,177
  • 1
  • 9
  • 9
3

Try the HTTP::Request module. Instances of this class are usually passed to the request() method of an LWP::UserAgent object.

Dave Horner
  • 405
  • 5
  • 10
coppro
  • 14,338
  • 5
  • 58
  • 73
3

Mojo::UserAgent is a great option too!

  use Mojo::UserAgent;
  my $ua = Mojo::UserAgent->new;

  # Say hello to the Unicode snowman with "Do Not Track" header
  say $ua->get('www.☃.net?hello=there' => {DNT => 1})->res->body;

  # Form POST with exception handling
  my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});
  if (my $res = $tx->success) { say $res->body }
  else {
    my ($err, $code) = $tx->error;
    say $code ? "$code response: $err" : "Connection error: $err";
  }

  # Quick JSON API request with Basic authentication
  say $ua->get('https://sri:s3cret@example.com/search.json?q=perl')
    ->res->json('/results/0/title');

  # Extract data from HTML and XML resources
  say $ua->get('www.perl.org')->res->dom->html->head->title->text;`

Samples direct from CPAN page. I used this when I couldn 't get LWP::Simple to work on my machine.

Dave Horner
  • 405
  • 5
  • 10
1

If it's in Unix and if LWP::Simple isn't installed, you can try:

my $content = `GET "http://trackMyPhones.com/"`;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Srihari Karanth
  • 2,067
  • 2
  • 24
  • 34
1

I think what Srihari might be referencing is Wget, but I would actually recommend (again, on *nix without LWP::Simple) to use cURL:

$ my $content = `curl -s "http://google.com"`;
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

The -s flag tells curl to be silent. Otherwise, you get curl's progress bar output on standard error every time.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tboz203
  • 379
  • 3
  • 13