Guzzle 6,获取请求字符串

Nic*_*iwi 17 php http guzzle guzzle6

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

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

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

原因是,我的请求失败并返回403,我想知道究竟发送了什么; 因为使用PostMan时同样的请求.

Moh*_*eer 18

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

$client->request('GET', '/get', ['debug' => true]);
Run Code Online (Sandbox Code Playgroud)

  • 这不会打印请求的正文,因此不会回答问题。 (4认同)
  • 再次,不必费力地复杂且难以使用而不花费几个小时寻找答案.调试某些东西应该不难.我原本以为你可以使用xdebug获取这些信息,但似乎不可能. (3认同)
  • 这样做的问题是,如果你的应用程序对输出渲染执行任何操作,你就会陷入困境,因为你什么都看不到.如果没有一些不必要的复杂的stdout重新路由,你就无法捕获它.哦,并为日志文件提供phpstream会产生curl请求错误.枪口设计为尽可能不透明吗? (2认同)
  • 放置 [ob_start](http://php.net/manual/en/function.ob-start.php) 和 [ob_get_clean](http://php.net/manual/en/function.ob-start.php)围绕`request`可以将调试结果转化为变量而不是标准输出。 (2认同)

dea*_*ina 7

Mohammed Safeer 的答案是正确的,但为了让那些刚刚将 debug 设置为 true 并在脚本执行过程中呈现一堆文本的人们更容易,您还可以执行以下操作:

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

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


arm*_*eys 5

根据此github问题中的评论,您可以使用历史中间件来存储/输出请求/响应信息。

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
}
Run Code Online (Sandbox Code Playgroud)

此处有一个更高级的示例: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.
}
Run Code Online (Sandbox Code Playgroud)