What's the simplest way to make a HTTP GET req

2019-02-05 12:56发布

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;
}

8条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-05 13:34

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

use LWP::Simple;
$content = get($url);
die "Can't GET $url" if (! defined $content);
查看更多
走好不送
3楼-- · 2019-02-05 13:34

I would use the LWP::Simple module.

查看更多
你好瞎i
4楼-- · 2019-02-05 13:42

LWP::Simple:

use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
查看更多
爷、活的狠高调
5楼-- · 2019-02-05 13:43

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

查看更多
爷、活的狠高调
6楼-- · 2019-02-05 13:45

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

查看更多
Evening l夕情丶
7楼-- · 2019-02-05 13:50

I think what Srihari might be referencing is Wget, but what I would actually recommend (again, on *nix without LSP::Simple) would be 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 stderr every time.

查看更多
登录 后发表回答