Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to make a HTTP GET request in Perl?

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; } 
like image 501
davr Avatar asked Sep 25 '08 17:09

davr


People also ask

How do I send a post request in Perl?

use LWP::UserAgent; use Data::Dumper; my $ua = new LWP::UserAgent; $ua->agent("AgentName/0.1 " . $ua->agent); my $req = new HTTP::Request POST => 'http://example.com'; $req->content('port=8', 'target=64'); #problem my $res = $ua->request($req); print Dumper($res->content);

How do you make HTTP requests?

The most common HTTP request methods have a call shortcut (such as http. get and http. post), but you can make any type of HTTP request by setting the call field to http. request and specifying the type of request using the method field.


1 Answers

LWP::Simple:

use LWP::Simple; $contents = get("http://YOUR_URL_HERE"); 
like image 173
Kevin Crumley Avatar answered Oct 18 '22 02:10

Kevin Crumley