为什么 GuzzleHttp 客户端在 Laravel/Lumen 上使用它发出网络请求时抛出 ClientException?

Why GuzzleHttp client throws ClientException when using it to make network request on Laravel/Lumen?

我目前正在使用 Laravel/Lumen 微 framework.Everything 构建一个金融微服务应用程序,一直按预期完美运行。我现在的问题是,我正在尝试使用 GuzzleHttp 客户端通过 ApiGateway 的 Api 调用向我的内部服务发出网络请求。问题是当我向内部服务发出请求时,它总是抛出 ClientException 异常。

ClientException.

Client error: GET http://127.0.0.1:8081/v1/admin resulted in a 401 Unauthorized response: {"error":"Unauthorized.","code":401}

我尝试使用 postman 向相同的内部服务发出网络请求;它工作正常。然而,出于某种原因仍然无法使用 GuzzleHttp。我不知道我做错了什么。请提供帮助。

这里是Api网关中的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);
}

InternalServiceController.php

   public function getAdmin(Request $request) {
        return $this->successResponse($this->authAdminService->getAdmin($request->header()));
    }

I am using Lumen version: 5.8 and GuzzleHttp Version: 6.3

您将 headers 作为 formParams 传递(第三个索引而不是第四个)。

试试下面的方法:

return $this->httpRequest('GET', 'admin', [], $header);

我在这里做了一些假设,希望对你有所帮助。

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);
 }