GuzzleHttp中有多个重复的uri参数

sko*_*and 5 guzzle

我正在访问Echo Nest API,这要求我重复相同的uri参数名称bucket。但是,我无法在Guzzle 6中完成这项工作。我从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
            ])
        ]
    );

    // ...
}
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗?

ori*_*nal 2

Guzzle 6中,您不再被允许传递任何聚合函数。每当您将数组传递给query配置时,它将使用以下函数进行序列化http_build_query

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

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

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
        ])
    ...
);
Run Code Online (Sandbox Code Playgroud)

handler否则,您可以将调整后的选项传递给该选项HandlerStack,该选项将在其堆栈中包含您的中间件处理程序。该人将读取一些新的配置参数,例如query_with_duplicates,构建可接受的查询字符串并相应地修改请求的 Uri。