【发布时间】:2019-08-08 09:47:22
【问题描述】:
我正在尝试将我的 API 连接到我的网站以检索数据。当用户连接时,会调用 API 以获取 JSON 格式的数据,但响应会为我提供 API 登录页面的 html。
我为此使用 Guzzle 6 和 laravel 5.8。
public static function getClient()
{
$url = config( 'test.default_api_url' );
$client = new Client([ 'base_uri' => $url, 'timeout' => 200.0 ]);
return $client;
}
public static function callApiOnce($method, $route, $options)
{
$client = self::getClient();
$response = $client->request($method, $route, $options)->getBody()->getContents();
if( $response )
{
$contents = (string) $response;
return $contents;
}
return false;
}
public static function callApiMany($routes)
{
$response = [];
foreach($routes as $route => $settings)
{
$json = self::callApiOnce(
$settings['method'],
$settings['route'],
$settings['options']
);
$response[$route] = $json;
}
return $response;
}
public function getHomeData()
{
$routes = [
"home_tile_1" => [
"method" => "GET",
"route" => "aggregates",
"options" => [
"query" => [
"user_id" => $_SESSION[ "userId" ],
"api_token" => $_SESSION[ "api_token" ],
"type" => "monthly",
"month" => "last"
],
"headers" => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $_SESSION[ "api_token" ]
]
]
]
];
$response = ApiRequestController::callApiMany( $routes );
return response()->json( [ "success" => true, "data" => $response ] );
}
我希望以 JSON 格式获取数据,但我只获取 API HTML 页面...
感谢您的关注。
【问题讨论】:
-
这里有几层,Arnaud。你在哪里期待 JSON?在
getHomeData方法中的$response变量中? -
嗨,是的,我想在 $response 中获取 JSON。它适用于邮递员,我得到 JSON 而不添加标题...
标签: html laravel http request guzzle