我在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响应的事实支持的,就好像没有发送正文一样。我在邮递员那查过了。正如您所看到的,正文指定了过滤器和分页,因此很容易看到我得到的结果实际上没有经过过滤。
Postman中的相同请求(使用body)可以完美地工作。
由于参数可以是StreamInterface类型,所以我创建了一个流,并将主体传递给它。也不管用。
发布于 2019-03-27 06:29:54
可以在不使用json_encode()的情况下创建简单的JSON请求...请参阅documentation。
use GuzzleHttp\Client;
$client = new Client([
'base_uri' => 'https://app.absence.io/api/v2',
'timeout' => 2.0
]);
$response = $client->request('POST', '/absences', ['json' => $body]);发布于 2019-03-27 17:03:45
发现问题了,其实我的帖子正文不是空的。事实证明,转储Request不会对消息中包含的实际正文有任何提示。
我可以推荐任何有类似问题的人使用http://httpbin.org/#/HTTP_Methods/post_post来调试POST主体。
最后,问题是我的content_type头拼写错误,因为服务器需要一个头Content-Type。因此,JSON数据被作为表单数据发送。
https://stackoverflow.com/questions/55366877
复制相似问题