【问题标题】:Set default query string in Guzzle 6在 Guzzle 6 中设置默认查询字符串
【发布时间】:2018-01-23 23:00:05
【问题描述】:

升级到 Guzzle6 后,我不知道如何为客户端设置默认查询字符串。

我有以下几点:

$client = new \GuzzleHttp\Client( [
    'base_uri' => 'http://api.example.org/',
    'query'   => ['key' => 'secretKey']
] );
$client->get( 'extract', ['query' => ['url' => $url]] );

在此请求中,我的默认查询字符串 key=secretKey 被忽略。

我怎样才能让它工作?

【问题讨论】:

    标签: php guzzle


    【解决方案1】:

    Guzzle v6 不支持客户端选项中的默认查询字符串。需要中间件。

    $handler = new HandlerStack();
    $handler->setHandler(new CurlHandler());
    
    //Add access token
    $handler->unshift(Middleware::mapRequest(function(RequestInterface $request) {
        return $request->withUri(Uri::withQueryValue($request->getUri(), 'key', 'value'));
    }));
    
    //Create client
    $this->client = new Client([
        'base_uri' => ''
        'handler' => $handler
    ]);
    

    来源见https://github.com/guzzle/guzzle/issues/1138

    【讨论】:

      【解决方案2】:

      您可以尝试使用“getConfig”方法获取默认的“查询”选项,然后将它们与新的“查询”选项合并,这里是一个示例:

      $client = new GuzzleHttp\Client([
          'base_uri' => 'http://api.example.org',
          'query'   => ['key' => 'secretKey']
      ]);
      

      然后你就可以轻松发送 GET 请求了:

      $client->get('/extract', [
          'query' =>  array_merge(
              $client->getConfig('query'),
              ['url' => $url]
           )
      ]);
      

      您可以在这里找到更多信息Request Options

      【讨论】:

        猜你喜欢
        • 2016-12-09
        • 2013-08-17
        • 1970-01-01
        • 1970-01-01
        • 2013-07-19
        • 1970-01-01
        • 1970-01-01
        • 2016-01-20
        • 2017-01-10
        相关资源
        最近更新 更多