[英]What's the simplest way to make a HTTP GET request in Perl?
我有一些用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 ::簡單:
use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");
LWP :: Simple具有您正在尋找的功能。
use LWP::Simple;
$content = get($url);
die "Can't GET $url" if (! defined $content);
看看LWP :: Simple 。 對於更多涉及的查詢,甚至還有一本關於它的書 。
我會使用LWP :: Simple模塊。
Mojo :: UserAgent也是一個很棒的選擇!
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;`
樣本直接來自CPAN頁面。 當我無法讓LWP :: Simple在我的機器上工作時,我使用了這個。
嘗試HTTP :: Request模塊。 此類的實例通常傳遞給LWP :: UserAgent對象的request()方法。
如果是在Unix中,如果沒有安裝LWP :: Simple,你可以嘗試:
my $content = `GET "http://trackMyPhones.com/"`;
我認為Srihari可能引用的是Wget ,但我實際上建議(再次,在沒有LWP :: Simple的* nix上)使用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>
-s
標志告訴curl是靜默的。 否則,每次都會在標准錯誤上獲得curl的進度條輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.