Symfony2 Guzzle存储cookie请求

时间:2016-11-29 21:36:09

标签: symfony guzzle guzzle6

尝试让我的Symfony2 Controller向支持的API发出请求。需要存储在第一次API请求时收到的cookie,以便在第二次请求中使用它。

这是我的控制器代码:

use Guzzle\Http\Client;

use Guzzle\Plugin\Cookie\CookiePlugin;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;


class DefaultController extends Controller
{

   public function verifyurlActionOK(Request $request)
   {


   $cookiePlugin = new CookiePlugin(new ArrayCookieJar());

   $client = new Client();

   $this->get('session')->set('client', $client);

   $client->addSubscriber($cookiePlugin);
   $request = $client->get('https://address/scanit?url='.$scantarget);
   $response = $request->send();
   }

   public function progressAction(Request $request)
   {
   $cli = $session->get('client');

   $crequest = $cli->get('https://address/progress');
   $response = $crequest->send();


   return $this->render('AppBundle:Default:progress.html.twig',
                        array(
                        'response'  => $cresponse->getBody()));
   }


}

尝试将Client设置为DefaultController类中的公共变量,并将其设置为Session(序列化)中的上述变量。两者似乎都不起作用,这里错误出现在progressAction的get()

[2016-11-29 16:22:46] request.CRITICAL: Uncaught PHP Exception Symfony\Component\Debug\Exception\FatalErrorException: "Error: Call to a member function get() on a non-object"

如何从progressAction中的verifyurlActionOK访问$ client?

谢谢,

2 个答案:

答案 0 :(得分:0)

最佳做法是创建包含Client实例的共享服务,并在两个操作中使用它。您可以存储cookie,而不是在会话中存储客户端。

Symfony有一个关于如何创建服务的良好文档页面:http://symfony.com/doc/current/service_container.html

答案 1 :(得分:0)

在progressAction方法中,您错过了从contanier获取会话。尝试添加第$session = $this->get('session')

例如:

public function progressAction(Request $request)
   {
   $session = $this->get('session')
   $cli = $session->get('client');

我建议你在会话中存储CookieJar对象(它实现可序列化并可以存储在会话中)而不是Client对象实例。例如:

public function verifyurlActionOK(Request $request)
{

    $cookieJar = $this->get('session')->get('cookie-jar', new ArrayCookieJar());
    $cookiePlugin = new CookiePlugin($cookieJar);

    $client = new Client();

    $client->addSubscriber($cookiePlugin);
    $request = $client->get('https://address/scanit?url='.$scantarget);
    $response = $request->send();
    $this->get('session')->set('cookie-jar', $cookieJar);

}

public function progressAction(Request $request)
{
    $cookieJar = $this->get('session')->get('cookie-jar');
    $cookiePlugin = new CookiePlugin($cookieJar);

    $cli = new Client();

    $cli->addSubscriber($cookiePlugin);

    $crequest = $cli->get('https://address/progress');
    $response = $crequest->send();


    return $this->render('AppBundle:Default:progress.html.twig',
        array(
            'response'  => $cresponse->getBody()));
}

希望这个帮助