首页 > 解决方案 > 为什么 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

标签: phplaravelmicroserviceslumen

解决方案


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

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

推荐阅读