调用未定义方法GuzzleHttpCommandResult::getBody()



我试图从json格式的外部API在Drupal中获得响应。我正在使用HTTP客户端管理器Drupal模块。现在我只能在数组中获得stdClass对象格式的响应,所有响应键值都缺失。

我的原始代码:

public function findPosts() {
$client = $this->getClient();
$params = array('client_Id' => "12345",
"client_Secret" => "42452454",
"scope" => "read");
$response = $client->FindPosts($params);
dpm($response);
return ['#markup' => $response];
}

输出下面的代码。我需要它看起来像[access_token] =>[type] =>持票人等。

stdClass Object
(
[__CLASS__] => GuzzleHttpCommandResult
[data:protected] => Array
(
[0] => eyJhbGciOiJIUzUxMiIsIn
[1] => bearer
[2] => 3600
[3] => 2022-11-09T10:48:47+00:00
[4] => read
[5] => MwA1ADkAZAA0AGIAZAA4AC0AOQAzADcA
[6] => 86400
[7] => 2022-11-10T09:48:47+00:00
)
)

当我尝试$response->getBody()或$response->getContent()或任何其他响应方法时,它返回以下错误。

Error: Call to undefined method GuzzleHttpCommandResult::getBody() in Drupalhttp_client_manager_exampleControllerExampleController->findPosts() (line 92 of modules/contrib/http_client_manager/modules/http_client_manager_example/src/Controller/ExampleController.php).
Drupalhttp_client_manager_exampleControllerExampleController->findPosts()
call_user_func_array(Array, Array) (Line: 123)
DrupalCoreEventSubscriberEarlyRenderingControllerWrapperSubscriber->DrupalCoreEventSubscriber{closure}() (Line: 564)
DrupalCoreRenderRenderer->executeInRenderContext(Object, Object) (Line: 124)
DrupalCoreEventSubscriberEarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
DrupalCoreEventSubscriberEarlyRenderingControllerWrapperSubscriber->DrupalCoreEventSubscriber{closure}() (Line: 169)
SymfonyComponentHttpKernelHttpKernel->handleRaw(Object, 1) (Line: 81)
SymfonyComponentHttpKernelHttpKernel->handle(Object, 1, 1) (Line: 58)
DrupalCoreStackMiddlewareSession->handle(Object, 1, 1) (Line: 48)
DrupalCoreStackMiddlewareKernelPreHandle->handle(Object, 1, 1) (Line: 106)
Drupalpage_cacheStackMiddlewarePageCache->pass(Object, 1, 1) (Line: 85)
Drupalpage_cacheStackMiddlewarePageCache->handle(Object, 1, 1) (Line: 49)
Asm89StackCors->handle(Object, 1, 1) (Line: 48)
DrupalCoreStackMiddlewareReverseProxyMiddleware->handle(Object, 1, 1) (Line: 38)
DrupalwebprofilerStackMiddlewareWebprofilerMiddleware->handle(Object, 1, 1) (Line: 51)
DrupalCoreStackMiddlewareNegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
StackStackedHttpKernel->handle(Object, 1, 1) (Line: 709)
DrupalCoreDrupalKernel->handle(Object) (Line: 19)

正如@bwaindwain提到的toArray()方法可以代替getBody()

toArray()方法适用于格式为

的响应。
[
{
"token": "4354iojegdjss"
}
]

然而,使用这种响应格式,所有键仍然消失:

{
"token": "4354iojegdjss"
}   

我对这个问题的修复是在src/api/resources/posts.json中手动添加responseModel:

{
"operations": {
"GetToken": {
"httpMethod": "POST",
"uri": "token",
"summary": "Get token",
},
"responseModel": "Token"
}
}
"models": {
"Token": {
"type": "object",
"location": "json",
"properties": {
"token": {
"location": "json",
"type": "string"
}
}
}
}

如果有人知道更好的修复方法,请评论。

相关内容

  • 没有找到相关文章

最新更新