什么使Perl中的HTTP GET请求的最简单的方法?(What's the simples

2019-07-04 00:29发布

我有一些代码,我用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;
}

Answer 1:

LWP ::简单:

use LWP::Simple;
$contents = get("http://YOUR_URL_HERE");


Answer 2:

LWP ::简单有你要找的功能。

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


Answer 3:

看看LWP ::简单 。 对于更复杂的查询,甚至还有一本关于它 。



Answer 4:

我会用LWP ::简单的模块。



Answer 5:

魔::用户代理是一个不错的选择呢!

  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 ::简单到我的机器上工作。



Answer 6:

尝试HTTP ::请求模块。 此类的实例通常传递到LWP ::用户代理对象的请求()方法。



Answer 7:

如果其在UNIX,如果没有LWP ::简单的安装,你可以试试

my $content = `GET "http://trackMyPhones.com/"`;


Answer 8:

我认为斯里里可能会被引用是Wget的 ,但我真的建议(同样,在没有LSP ::简单的* nix)是使用卷曲

$ 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保持沉默。 否则,你会得到标准错误每次卷曲的进度条输出。



文章来源: What's the simplest way to make a HTTP GET request in Perl?