【问题标题】:Multiple duplicate uri parameters in GuzzleHttpGuzzleHttp 中的多个重复 uri 参数
【发布时间】:2017-12-28 20:36:24
【问题描述】:

我正在访问 Echo Nest API,这需要我重复相同的 uri 参数名称 bucket。但是我无法在 Guzzle 6 中完成这项工作。I read a similar issue from 2012,但是这种方法不起作用。

我已尝试将其手动添加到查询字符串中,但没有成功。

一个示例 API 调用可能是:

http://developer.echonest.com/api/v4/song/search?format=json&results=10&api_key=someKey&artist=Silbermond&title=Ja&bucket=id:spotify&bucket=tracks&bucket=audio_summary

这是我的示例客户端:

/**
 * @param array $urlParameters
 * @return Client
 */
protected function getClient()
{
    return new Client([
        'base_uri' => 'http://developer.echonest.com/api/v4/',
        'timeout'  => 5.0,
        'headers' => [
            'Accept' => 'application/json',
        ],
        'query' => [
            'api_key' => 'someKey',
            'format' => 'json',
            'results' => '10',
            'bucket' => 'id:spotify'         // I need multiple bucket parameter values with the 'bucket'-name
    ]);
}

/**
 * @param $artist
 * @param $title
 * @return stdClass|null
 */
public function searchForArtistAndTitle($artist, $title)
{
    $response = $this->getClient()->get(
        'song/search?' . $this->generateBucketUriString(),
        [
            'query' => array_merge($client->getConfig('query'), [
                'artist' => $artist,
                'title' => $title
            ])
        ]
    );

    // ...
}

你能帮帮我吗?

【问题讨论】:

    标签: guzzle


    【解决方案1】:

    Guzzle 6 中,您不能再传递任何聚合函数。每当您将数组传递给query 时,使用http_build_query 函数配置will be serialized

    if (isset($options['query'])) {
        $value = $options['query'];
        if (is_array($value)) {
            $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
        }
    

    为避免这种情况,您应该自己序列化查询字符串并将其作为字符串传递。

    new Client([
        'query' => $this->serializeWithDuplicates([
            'bucket' => ['id:spotify', 'id:spotify2']
        ]) // serialize the way to get bucket=id:spotify&bucket=id:spotify2
    ...
    $response = $this->getClient()->get(
        ...
            'query' => $client->getConfig('query').$this->serializeWithDuplicates([
                'artist' => $artist,
                'title' => $title
            ])
        ...
    );
    

    否则,您可以将调整后的HandlerStack 传递给handler 选项,它的堆栈中将包含您的中间件处理程序。它会读取一些新的配置参数,比如query_with_duplicates,相应地构建可接受的查询字符串和modify Request's Uri。

    【讨论】:

      猜你喜欢
      • 2017-05-23
      • 2016-01-22
      • 2011-02-22
      • 2020-06-16
      • 1970-01-01
      • 2020-11-27
      • 2015-08-03
      • 2021-11-04
      • 2020-07-09
      相关资源
      最近更新 更多