Copying cookies from first response to next request

馋奶兔 提交于 2019-12-10 22:58:59

问题


I'm sending a first HTTP request out using HttpRequest->send(), and I receive a 302 response with the following Set-Cookie headers:

  • Set-Cookie: SESSION_SCOPE=1; path=/
  • Set-Cookie: III_EXPT_FILE=aa2171; path=/; domain=.example.com
  • Set-Cookie: III_SESSION_ID=193a3ce5aaadea85937c25cd0430332f; domain=.example.com; path=/

When I use HttpRequest->getResponseCookies(), this is what the extracted content looks like:

Array ( 
 - [0] => stdClass Object ( [cookies] => Array ( [SESSION_SCOPE] => 1 ) [extras] => Array ( ) [flags] => 0 [expires] => 0 [path] => / [domain] => ) 
 - [1] => stdClass Object ( [cookies] => Array ( [III_EXPT_FILE] => aa2171 ) [extras] => Array ( ) [flags] => 0 [expires] => 0 [path] => / [domain] => .example.com ) 
 - [2] => stdClass Object ( [cookies] => Array ( [III_SESSION_ID] => 193a3ce5aaadea85937c25cd0430332f ) [extras] => Array ( ) [flags] => 0 [expires] => 0 [path] => / [domain] => .example.com )
 ) 

Now I need to copy these cookies over to the next outgoing request to the redirected location. I'm using HttpRequest->setCookies(), in which the argument is the array that was returned from the previous getResponseCookies() call.

What I see in the outgoing request is:

Cookie: 0%5Bcookies%5D%5BSESSION_SCOPE%5D=1; 0%5Bflags%5D=0; 0%5Bexpires%5D=0; 0%5Bpath%5D=%2F; 0%5Bdomain%5D=; 1%5Bcookies%5D%5BIII_EXPT_FILE%5D=aa2171; 1%5Bflags%5D=0; 1%5Bexpires%5D=0; 1%5Bpath%5D=%2F; 1%5Bdomain%5D=.example.com; 2%5Bcookies%5D%5BIII_SESSION_ID%5D=193a3ce5aaadea85937c25cd0430332f; 2%5Bflags%5D=0; 2%5Bexpires%5D=0; 2%5Bpath%5D=%2F; 2%5Bdomain%5D=.example.com

My questions are:

  1. What's the correct way of doing this? Because clearly the array indices are being added to the header too
  2. How can I prevent the url-encoding of the parameters?
  3. How can I prevent the 'path' and 'domain' attributes from being added to the header?

Thanks!


回答1:


Solved it. In my inherent newbie-ness, I was using separate HttpRequest objects for the first and second transactions.

Instead, after creating the first request, I simply called the enableCookies() method and re-used the same object to send the second request.

In a nutshell:

$URL1 = (main url);

/* Construct and send the first request */
$r1 = new HttpRequest ($URL1, METH_POST);
$r1->enableCookies();
$r1->setPostFields (...);
$r1->send();

/* Verify that the response is in fact a 302 first! */

$URL2 = $URL1 . $r1->getResponseHeader("Location");

/* Construct and send the second request */
$r1 = new HttpRequest ($URL2, METH_POST);
$r1->send();

/* Success! */


来源:https://stackoverflow.com/questions/4212442/copying-cookies-from-first-response-to-next-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!