【问题标题】:Guzzle Get request with headers and query stringGuzzle 获取带有标头和查询字符串的请求
【发布时间】:2021-10-11 05:18:36
【问题描述】:

我正在尝试使用 Guzzle 客户端通过 GET 请求获取数据。我将标头与 JWT 令牌和查询参数一起使用,如下所示:

function fetchUserByEmployeeId(string $employeeId): JsonResponse
    {
        $headers = $this->getHeaders();
        $query = ['$filter' => "employeeId eq $employeeId", '$select' => 'displayName,givenName,postalCode,employeeId,id'];
        try {
            $result = $this->client->request('GET', self::FIND_USER_BY_EMPLOYEE_ID_URL, [
                'headers' => $headers,
                'query' => $query,
                'debug' => true
            ]);
            return JsonResponse::fromJsonString($result->getBody()->getContents());
        } catch (RequestException $exception) {
            throw $exception;
        }
    }

不幸的是,我收到了如下错误:

如果我删除 $query 它将起作用。我的查询参数有问题吗?我不知道。根据 Guzzle 文档,它似乎没问题:https://docs.guzzlephp.org/en/stable/request-options.html#query

【问题讨论】:

  • 你能用过滤查询和选择查询显示你想要的最终网址是什么吗?

标签: php symfony get query-string guzzle


【解决方案1】:

幸运的是我已经解决了这个问题。问题在于传递参数。 $employeeId,应该用引号引起来。如下:

function fetchUserByEmployeeId(string $employeeId): JsonResponse
    {
        $headers = $this->getHeaders();
        $query = ["\$filter" => "employeeId eq '$employeeId'", "\$select" => "displayName,givenName,postalCode,employeeId,id"];
        try {
            $result = $this->client->request('GET', self::FIND_USER_BY_EMPLOYEE_ID_URL, [
                RequestOptions::HEADERS => $headers,
                RequestOptions::QUERY => $query,
                'debug' => true
            ]);
            return JsonResponse::fromJsonString($result->getBody()->getContents());
        } catch (RequestException $exception) {
            throw $exception;
        }
    }

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2014-06-15
    • 2022-01-23
    相关资源
    最近更新 更多