在 Guzzle6/PSR7 中开机自检请求时空正文



我在PSR7风格中使用Guzzle6,因为它与Hawk身份验证很好地集成在一起。现在,我在向请求中添加正文时遇到问题。

private function makeApiRequest(Instructor $instructor): ResponseInterface
{
    $startDate = (new CarbonImmutable('00:00:00'))->toIso8601ZuluString();
    $endDate = (new CarbonImmutable('00:00:00'))->addMonths(6)->toIso8601ZuluString();
    $instructorEmail = $instructor->getEmail();
    $body = [
        'skip' => 0,
        'limit' => 0,
        'filter' => [
            'assignedTo:user._id' => ['email' => $instructorEmail],
            'start' => ['$gte' => $startDate],
            'end' => ['$lte' => $endDate],
        ],
        'relations' => ['reasonId']
    ];
    $request = $this->messageFactory->createRequest(
        'POST',
        'https://app.absence.io/api/v2/absences',
        [
            'content_type' => 'application/json'
        ],
        json_encode($body)
    );
    $authentication = new HawkAuthentication();
    $request = $authentication->authenticate($request);
    return $this->client->sendRequest($request);
}

当我var_dump $request变量时,我在请求中看不到任何正文。API 响应就像没有发送正文一样,这一事实支持了这一点。我在邮递员中交叉检查了这一点。如您所见,正文指定了过滤器和分页,因此很容易看出我得到的结果实际上没有被过滤。

邮递员(带身体(中的相同请求完美无缺。

由于参数可以是 StreamInterface 类型,因此我创建了一个流并将正文传递给它。也没用。

可以在不使用json_encode()的情况下创建简单的JSON请求...请参阅文档。

use GuzzleHttpClient;
$client = new Client([
    'base_uri' => 'https://app.absence.io/api/v2',
    'timeout'  => 2.0
]);
$response = $client->request('POST', '/absences', ['json' => $body]);

发现问题,实际上我的 POST 正文不是空的。事实证明,转储Request不会暗示消息中包含的实际正文的任何内容。

我可以建议任何有类似问题的人使用 http://httpbin.org/#/HTTP_Methods/post_post 来调试 POST 正文。

最后,问题是我的content_type标头拼写错误,因为服务器期望标头Content-Type。因此,JSON 数据作为表单数据发送。

最新更新