Guzzle 6,获取请求字符串

Guzzle 6, get request string

有没有办法在发送之前或之后将完整的请求打印成字符串?

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

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

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

根据 Guzzle 文档,有调试选项,这里是来自 guzzle 文档的 link http://guzzle.readthedocs.org/en/latest/request-options.html#debug

$client->request('GET', '/get', ['debug' => true]);

根据 a comment in this github issue,您可以使用历史中间件来 store/output request/response 信息。

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.
}

Mohammed Safeer 的回答是正确的,但为了让刚刚将调试发送到 true 并在脚本执行过程中呈现一堆文本的人更容易,您还可以执行以下操作:

$debug = fopen("path_and_filename.txt", "a+");
$client->request('GET', '/get', ['debug' => $debug ]);

这会将调试流输出到给定文件,而不是“中断”请求的执行。