我用Laravel做了一个小而简单的web应用程序,我使用API从其中获取数据,并以用户友好的方式可视化。为了处理/获取来自App的数据,我在我的应用程序中创建了一个BaseRepository,但是我得到了这个错误:"curl_setopt_array(): supplied resource is not a valid cURL handle resource"
下面是它看起来的样子

如果有人能帮上忙那就太好了。
下面是我的代码:
<?php
namespace App\Repositories;
// Class BaseRepository.
class BaseRepository
{
public $curl = null;
public function __construct()
{
$this->curl = curl_init();
}
public function getAccessToken()
{
curl_setopt_array($this->curl, array(
CURLOPT_URL => "https://identity.vwgroup.io/oidc/v1/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "grant_type=client_credentials&client_id=MY_ID_GOES_HERE&client_secret=MY_CLIENT_SECRET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/x-www-form-urlencoded",
"Postman-Token: 84e72567-25d5-42ba-8a94-fe88e6bcc41d",
"cache-control: no-cache",
),
));
$response = curl_exec($this->curl);
$err = curl_error($this->curl);
curl_close($this->curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// Convert JSON string to Object
$responseObject = json_decode($response);
$accessToken = $responseObject->access_token; // Access Object data
return $accessToken;
}
}
public function getCountries()
{
curl_setopt_array($this->curl, array(
CURLOPT_URL => "https://api.productdata.vwgroup.com/v2/countries",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Authorization: bearer " . $this->getAccessToken(),
"Postman-Token: e6625e0a-fc50-4382-8812-8d151457dcab,67edecb8-64bd-4c93-9892-ec1061d5f210",
"cache-control: no-cache,no-cache",
),
));
$response = curl_exec($this->curl);
$err = curl_error($this->curl);
curl_close($this->curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// Convert JSON string to Object
$responseObject = json_decode($response, true);
$data = array('data' => $responseObject['data']);
return $data;
}
}
}发布于 2019-03-13 08:33:15
我的猜测是,您的子库类之一正在定义一个__construct()方法,而您忘记了在其中调用parent::__construct(),因此永远不会调用curl_init()方法。
编辑: Phil的评论是你的问题的另一个很可能的原因。在一个方法中调用curl_close()将阻止下一个方法使用共享cURL初始化。
我真的建议将curl_init()移动到每个存储库方法。您的请求不相关,并且可能共享不同的选项和配置。通过修改单个cURL实例,您可能会共享您不想要的选项。它还允许您在每个子库类中使用__construct(),而不必担心BaseRepository及其构造函数(可以删除)。
https://stackoverflow.com/questions/55130532
复制相似问题