【发布时间】:2018-08-22 16:37:18
【问题描述】:
我遇到了一个无法解决的问题,我有一个使用 Guzzle 连接到 RESTful api 的类,它在修补程序中工作,但在控制器中,我总是使用相同的连接得到 401 未经授权的错误数据。
ApiConnectionClass
use App\ApiData;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7;
class ApiConnectionClass
{
var $conn_data;
var $client;
public function __construct()
{
$this->conn_data = ApiData::findOrFail(1);
$this->client = new Client(['base_uri' => $this->conn_data->url]);
}
public function lista_pruebas(){
try{
$response = $this->client->request('GET', 'pruebas/detalles', [
'verify' => false,
'headers' => ['Authorization' => 'Bearer ' . $this->conn_data->access_token],
]);
} catch (GuzzleException $e) {
dump(Psr7\str($e->getRequest()));
if ($e->hasResponse()) {
dd(Psr7\str($e->getResponse()));
}
}
return json_decode($response->getBody()->getContents());
}
在修补程序中我得到正确的 json 响应
$api = new App\Classes\ApiConnectionClass();
$api->lista_pruebas();
ApiController
use App\Classes\ApiConnectionClass;
class ApiController extends Controller
{
public function lista_pruebas(){
$api = new ApiConnectionClass();
$lista = $api->lista_pruebas();
return view('pruebas.index', compact('lista'));
}
}
从控制器调用的 ApiConnectionClass 响应
""" HTTP/1.0 401 Unauthorized\r\n 日期:2018 年 8 月 22 日星期三 16:20:58 GMT\r\n 服务器:Apache/2.4.33 (Win64) PHP/7.2.4\r\n 变化: 授权\r\n X-Powered-By: PHP/7.2.4\r\n Cache-Control: no-cache, 私有\r\n 内容长度: 13\r\n 连接: 关闭\r\n 内容类型: 文本/html; charset=UTF-8\r\n \r\n 未经授权。 """
【问题讨论】:
-
我的2cents英文码,对你有很大帮助。祝你好运!