GuzzleHttp中有多个重复的uri参数

时间:2015-11-12 13:07:33

标签: guzzle

我正在访问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
            ])
        ]
    );

    // ...
}

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

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选项,该调整后的modify将在其堆栈中包含您的中间件处理程序。那个人会读一些新的配置参数,比如query_with_duplicates,构建可接受的查询字符串,{{3}}请求的Uri相应地。