php - 为什么 GuzzleHttp 客户端在 Laravel/Lumen 上使用它发出网络请求时会抛出 ClientException?
问题描述
我目前正在使用 Laravel/Lumen 微框架构建一个金融微服务应用程序。一切都按预期完美运行。我现在的问题是我正在尝试通过ApiGateway
使用GuzzleHttp
客户端的 Api 调用向我的内部服务发出网络请求。问题是当我向内部服务发出请求时,它总是抛出ClientException异常。
客户端异常。
客户端错误:
GET http://127.0.0.1:8081/v1/admin
导致401 Unauthorized
响应:{"error":"Unauthorized.","code":401}
我尝试使用postman向相同的内部服务发出网络请求;它工作正常。但是,由于某种原因仍然无法使用GuzzleHttp
. 我不知道我做错了什么。请您的协助将不胜感激。
这是 ApiGateway 中的 httpClient.php。
//Constructor method
public function __construct() {
$this->baseUri = config('services.auth_admin.base_uri');
}
public function httpRequest($method, $requestUrl, $formParams = [], $headers = []) {
//Instantiate the GazzleHttp Client
$client = new Client([
'base_uri' => $this->baseUri,
]);
//Send the request
$response = $client->request($method, $requestUrl, ['form_params' => $formParams, 'headers' => $headers]);
//Return a response
return $response->getBody();
}
//Internal Service Communication in ApiGateway**
public function getAdmin($header) {
return $this->httpRequest('GET', 'admin', $header);
}
内部服务控制器.php
public function getAdmin(Request $request) {
return $this->successResponse($this->authAdminService->getAdmin($request->header()));
}
我正在使用 Lumen 版本:5.8 和 GuzzleHttp 版本:6.3
解决方案
我在这里做了一些假设,希望对您有所帮助。
PHP 不支持跳过可选参数,因此您应该在调用时传递一个空数组 [] httpRequest()
。
public function httpRequest($method, $requestUrl, $formParams = [], $headers = [], $type='json', $verify = false) {
//Instantiate the GazzleHttp Client
$client = new Client([
'base_uri' => $this->baseUri,
]);
//the request payload to be sent
$payload = [];
if (!$verify) {
$payload['verify'] = $verify; //basically for SSL and TLS
}
//add the body to the specified payload type
$payload[$type] = $formParams;
//check if any headers have been passed and add it as well
if(count($headers) > 0) {
$payload['headers'] = $headers;
}
//Send the request
$response = $client->request($method, $requestUrl, $payload);
//Return a response
return $response->getBody();
}
现在,当您没有传入任何 form_params 或 body 时,您需要以这种方式调用它
//Internal Service Communication in ApiGateway**
public function getAdmin($header) {
return $this->httpRequest('GET', 'admin', [], $header);
}
推荐阅读
- powerbi - 根据同一表的另一列获取特定列的计数 - Power BI
- openvino - 问:如何获取 dldt buildinfo?
- django - 在 React 前端显示 rtsp 流
- excel - 宏按钮将文件移动到另一个文件夹
- node.js - 如何在构建模板时修复离子错误
- javascript - 如何以数组中的对象为条件在 Json 表单中使用规则?
- google-cloud-platform - 从 Google Cloud 内部 IP 调用 Google Cloud 存储桶
- blender - Blender:没有对象附加纹理
- javascript - 仅替换单击元素的内部部分
- javascript - React - useReducer 和 useState