2017-07-31 66 views
5

我正在使用Guzzle登錄我的API站點,並且在使用正確的憑證進行登錄時,我找回了一個帶有RefreshToken的cookie,以便在下次調用時發送它,這裏是我簡單(並且工作良好)的代碼:現在GuzzleHttp:如何從POST響應中保存cookie並在下一次POST中使用它?

$newCookies = $response->getHeader('set-cookie'); 

,我需要在接下來的調用使用這個cookie,我知道:

$client = new Client(array(
      'cookies' => true 
     )); 


     $response = $client->request('POST', 'http://myapi.com/login', [ 
      'timeout' => 30, 
      'form_params' => [ 
       'email' => $request->get('email'), 
       'password' => $request->get('password'), 
      ] 
     ]); 

和我回去用一個cookie正確的反應,我可以通過看餅乾Guzzle可以爲我保存cookie並在下次調用時使用「CookieJar」或「SessionCookieJar」自動發送(或不發送),我試圖使用它,但我沒有E在「罐子」的餅乾,這裏是我做了什麼:

$cookieJar = new SessionCookieJar('SESSION_STORAGE', true); 

     $client = new Client([ 
      'cookies' => $cookieJar 
     ]); 

     $response = $client->request .... 

,但是,當我得到的餅乾從回來後,我只能通過看出來:

$newCookies = $response->getHeader('set-cookie'); 

它不在cookieJar中,所以它不會在下次調用中發送它。 我在這裏錯過了什麼?

謝謝!

+0

http://docs.guzzlephp.org/en/stable/quickstart.html#cookies。您需要爲登錄請求設置jar以便收集cookie – Phil

+0

感謝您的回答,我試圖在請求中設置它,並且在新客戶端init中沒有任何工作(我已經多次閱讀該手冊),你可以添加一些代碼嗎? –

回答

1

作爲每文檔here['cookies' => true]指示使用共享餅乾罐所有請求的,而['cookies' => $jar]所示的使用一個特定餅乾罐($jar),用於與客戶機的請求/響應使用。所以,你需要爲使用:

$client = new Client(array(
    'cookies' => true 
)); 


$response = $client->request('POST', 'http://myapi.com/login', [ 
    'timeout' => 30, 
    'form_params' => [ 
     'email' => $request->get('email'), 
     'password' => $request->get('password'), 
    ] 
]); 

// and using the same client 

$response = $client->request('GET', 'http://myapi.com/next-url'); 

// or elsewhere ... 

$client = new Client(array(
    'cookies' => true 
)); 

$response = $client->request('GET', 'http://myapi.com/next-url'); 

$jar = new CookieJar; 

$client = new Client(array(
    'cookies' => $jar 
)); 


$response = $client->request('POST', 'http://myapi.com/login', [ 
    'timeout' => 30, 
    'form_params' => [ 
     'email' => $request->get('email'), 
     'password' => $request->get('password'), 
    ] 
]); 

// and using the same client 

$response = $client->request('GET', 'http://myapi.com/next-url'); 

// or elsewhere ... 

$client = new Client(array(
    'cookies' => $jar // the same $jar as above 
)); 

$response = $client->request('GET', 'http://myapi.com/another-url'); 
+0

謝謝,你是對的,我只是想通了:) – EranLevi

相關問題