【问题标题】:Guzzle 6, get request stringGuzzle 6,获取请求字符串
【发布时间】:2015-12-09 21:37:15
【问题描述】:

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

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

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

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

【问题讨论】:

标签: php http guzzle guzzle6


【解决方案1】:

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

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

【讨论】:

  • 这个问题是如果你的应用程序对输出渲染做任何事情,你会被卡住,因为你什么都看不到。如果没有对标准输出进行一些不必要的复杂重新路由,您将无法捕获它。哦,向日志文件提供 phpstream 会导致 curl 请求错误。 guzzle 是否设计得尽可能不透明?
  • ob_startob_get_clean 放在request 周围可以让您将调试结果放入变量而不是标准输出。
  • 再一次,如果不花几个小时寻找答案,不必要的复杂和难以使用。调试某些东西应该不难。我原以为您可以使用 xdebug 获取此信息,但似乎不可能。
  • 这不会打印请求的正文,因此不会回答问题。
【解决方案2】:

根据a comment in this github issue,您可以使用历史中间件来存储/输出请求/响应信息。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2015-10-30
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多