代码之家  ›  专栏  ›  技术社区  ›  DarkFenix

使用GuzzleHttp从HTTP调用获取cookie的值

  •  4
  • DarkFenix  · 技术社区  · 8 年前

    我现在使用GuzzleHttp发出HTTP请求,首先我发出登录的POST请求。asp,它返回一个带有Set Cookie的响应,该Cookie的值是我未来请求所需的值

    enter image description here

    当我检查我获得的答案时,我得到以下信息

    enter image description here

    如前所述,我得到了除Set Cookie之外的所有密钥,会发生什么?如何获取此值?我正在使用 "guzzlehttp/guzzle": "^6.3", 或者我可以使用其他工具获取它吗?

        $jar = new CookieJar;
    
        $client = new Client([
            'base_uri' =>'miurl/',
            'timeout'  => 10.0,
            'cookies' => $jar
        ]);
    
        $response = $client->request('POST', 'login.asp',  [
            'form_params' => [
                'pws' => '',//data password
                'user' => '',//data user
            ]
        ]);
    
        //Request require coookies
    
        $response = $client->request('POST', 'goform/Wls',  [
            'form_params' => [
                /*Form´Params*/
            ],
           //if I manually add a correct userid the post application works fine
            'headers' => [
                //Require cookie param userid 
                'Cookie' => 'LANG_COOKIE=lang_span; userid=1524324306',
            ]
        ]);
    

    Alternatively, I used this configuration without being able to obtain the cookie yet

    使用postman检查一下答案,正确登录后仍然在同一页面上,但使用javascript重定向,这会影响吗?

    <script language='JavaScript'>window.location='/admin/cable-Systeminfo.asp';</script>
    </html>
    

    我直接请求hitron technologies cgnv22路由器管理mac过滤,我想提供更多信息,但这是敏感信息

    1 回复  |  直到 8 年前
        1
  •  8
  •   Gustavo Straube    8 年前

    似乎您以正确的方式提出了请求,传递了 CookieJarInterface 。但是,您不应该期望 Set-Cookie 标题。相反,请检查 罐子 检查返回了哪些Cookie。

    以下示例显示了如何迭代所有Cookie:

    $client = new \GuzzleHttp\Client();
    
    $jar = new \GuzzleHttp\Cookie\CookieJar();
    $request = $client->request('GET', 'https://www.google.com/', [
        'cookies' => $jar
    ]);
    
    $it = $jar->getIterator();
    while ($it->valid()) {
        var_dump($it->current());
        $it->next();
    }
    

    以下是上述代码段的示例输出:

    object(GuzzleHttp\Cookie\SetCookie)#36 (1) {
      ["data":"GuzzleHttp\Cookie\SetCookie":private]=>
      array(9) {
        ["Name"]=>
        string(3) "NID"
        ["Value"]=>
        string(132) "130=dmyl6v*******"
        ["Domain"]=>
        string(11) ".google.com"
        ["Path"]=>
        string(1) "/"
        ["Max-Age"]=>
        NULL
        ["Expires"]=>
        int(1542242169)
        ["Secure"]=>
        bool(false)
        ["Discard"]=>
        bool(false)
        ["HttpOnly"]=>
        bool(true)
      }
    }
    

    请参阅 CookieJar 班 source 有关如何访问返回的Cookie的更多信息。此外,您可以查看 docs 对于 ArrayIterator 班