Guzzle 6,获取请求字符串

新手上路,请多包涵

有没有一种方法可以在发送之前或之后将完整的请求作为字符串打印出来?

 $res = (new GuzzleHttp\Client())->request('POST', 'https://endpoint.nz/test', [ 'form_params' => [ 'param1'=>1,'param2'=>2,'param3'=3 ] ] );

我如何将该请求视为字符串? (不是回应)

原因是,我的请求失败并返回 403,我想知道到底发送了什么;因为使用 PostMan 时同样的请求有效。

原文由 Nicekiwi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 371
2 个回答

根据 这个 github issue 中的评论,您可以使用 history 中间件来存储/输出请求/响应信息。

 use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

$container = [];
$history = Middleware::history($container);

$stack = HandlerStack::create();
// Add the history middleware to the handler stack.
$stack->push($history);

$client = new Client(['handler' => $stack]);

$client->request('POST', 'http://httpbin.org/post',[
    'body' => 'Hello World'
]);

// Iterate over the requests and responses
foreach ($container as $transaction) {
    echo (string) $transaction['request']->getBody(); // Hello World
}

这里有一个更高级的例子: http ://docs.guzzlephp.org/en/stable/testing.html#history-middleware

 use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

$container = [];
$history = Middleware::history($container);

$stack = HandlerStack::create();
// Add the history middleware to the handler stack.
$stack->push($history);

$client = new Client(['handler' => $stack]);

$client->request('GET', 'http://httpbin.org/get');
$client->request('HEAD', 'http://httpbin.org/get');

// Count the number of transactions
echo count($container);
//> 2

// Iterate over the requests and responses
foreach ($container as $transaction) {
    echo $transaction['request']->getMethod();
    //> GET, HEAD
    if ($transaction['response']) {
        echo $transaction['response']->getStatusCode();
        //> 200, 200
    } elseif ($transaction['error']) {
        echo $transaction['error'];
        //> exception
    }
    var_dump($transaction['options']);
    //> dumps the request options of the sent request.
}

原文由 armyofda12mnkeys 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏