2012-03-01 68 views
2

要優化我的Perl應用程序我需要使用異步 HTTP請求,所以我可以在HTTP響應完成後處理其他操作。所以我相信我唯一的選擇是使用HTTP::Async模塊。這對簡單的請求工作正常,但我需要從一個響應中捕獲cookie頭,並將其與下一個響應發送,所以我需要閱讀標頭。我的代碼是:是否可以使用Perl HTTP :: Async模塊讀取標題?

   ... 

      $async->add($request); 
      while ($response = $async->wait_for_next_response) 
      { 
       threads->yield(); yield(); 
      } 
      $cookie = $response->header('Set-Cookie'); 
      $cookie =~ s/;.*$//; 
      $request->header('Cookie' => $cookie); 

      ... 

,但它不工作,因爲它與一個錯誤結束未定義的值無法調用「頭」。顯然$responseundef。如何在$response獲得undef之前獲得標題?

+0

很少有很多異步HTTP模塊。您可能想要轉向基於事件的模塊,如AnyEvent :: HTTP或POE :: Component :: Client :: HTTP,並在回調中處理您的響應。您不應該爲您的整個應用程序使用POE或AnyEvent。 – MkV 2012-03-02 01:00:43

回答

4
while ($response = $async->wait_for_next_response) 
{ 
    threads->yield(); yield(); 
} 

保證沒有完成,直到$response爲假。唯一的假值wait_for_next_response將返回undef。您需要提取循環內的cookie,或緩存循環內的最後一個良好響應。

喜歡的東西

my $last_response; 
while ($response = $async->wait_for_next_response) 
{ 
    $last_response = $response; 
    threads->yield(); yield(); 
} 

應該工作,雖然我不知道你所需要的循環可言。沒有完整的程序很難說。

+0

謝謝。我剛剛測試的其他選項是放入循環以下命令:$ cookie = $ response-> header('Set-Cookie')。如果((定義$ response-> header('Set-Cookie'))&&($ response-> header('Set-Cookie')ne''));「*** \ n」 – 2012-03-01 20:43:43

相關問題