怎么用guzzle得到饼干?

时间:2017-11-17 18:10:19

标签: guzzle

Guzzle网站的文档非常薄弱。我意识到我需要查看源代码以使用库的所有功能,但我仍然无法完全理解源代码。

如何从任何网站获取Guzzle的Cookie?要看什么课?

1 个答案:

答案 0 :(得分:1)

guzzle中的Cookie表示是PSR-7ServerRequestInterface implementation的一部分,例如ServerRequest类。在类中定义了一个数组属性$cookieParams。对于此变量,您可以通过调用$_COOKIE来分配fromGlobals()变量(通过调用静态方法$_COOKIE)或您选择的数组(包括withCookieParams())。要阅读$cookieParams数组的内容,您只需拨打getCookieParams()

使用fromGlobals()的示例 - 具有ServerRequest工厂的角色:

<?php

use GuzzleHttp\Psr7\ServerRequest;

/**
 * Create a ServerRequest instance, populated with superglobals:
 * $_GET
 * $_POST
 * $_COOKIE
 * $_FILES
 * $_SERVER
 */
$serverRequest = ServerRequest::fromGlobals();

// Display the content of $_COOKIE.
var_dump($serverRequest->getCookieParams());

直接创建ServerRequest实例并将cookie数组分配给它的副本的示例 - 以保持请求对象的不变性:

<?php

use GuzzleHttp\Psr7\ServerRequest;

// Directly create a ServerRequest instance.
$serverRequest = new ServerRequest('GET', 'http://localhost/mypath?var=somevar#myfragment', [], NULL, '1.1', $_SERVER);

// Create a clone instance with the specified cookies array.
$serverRequest = $serverRequest->withCookieParams($_COOKIE);

// Display the content of the cookies list.
var_dump($serverRequest->getCookieParams());

还有另一个实现,即GuzzleHttp\Cookie\CookieJarInterface的实现,例如类GuzzleHttp\Cookie\CookieJar(请参阅here)这在http://docs.guzzlephp.org上有记录,位于:

CookieJar课程中,您可以在构造函数中指定$cookieArray并使用一些方法来处理其值(getCookieValue()getCookieByName()setCookie()等)。