【问题标题】:Guzzle Request query paramsGuzzle 请求查询参数
【发布时间】:2023-04-02 18:02:01
【问题描述】:

我有一个使用 gullzehttp 的方法,想将其更改为池,并且池实现了 Request 方法

<?php
use GuzzleHttp\Client;
$params = ['password' => '123456'];
$header = ['Accept' => 'application/xml'];
$options = ['query' => $params, 'headers' => $header];
$response = $client->request('GET', 'http://httpbin.org/get', $options);

我需要更改为 Request 方法,但我在文档中找不到如何在 Request 中发送查询字符串变量

<?php
use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://httpbin.org/get', $options);

【问题讨论】:

    标签: php guzzle


    【解决方案1】:

    您需要将查询作为字符串添加到 URI。

    为此,您可以使用http_build_queryguzzle helper function 将参数数组转换为编码的查询字符串:

    $uri = new Uri('http://httpbin.org/get');
    
    $request = new Request('GET', $uri->withQuery(GuzzleHttp\Psr7\build_query($params)));
    
    // OR 
    
    $request = new Request('GET', $uri->withQuery(http_build_query($params)));
    

    【讨论】:

    • 谢谢。似乎他们的6.5 Docs 会造成混淆,看起来您可以在$options 数组中添加查询参数。
    【解决方案2】:

    我也很难弄清楚如何正确放置new Request() 参数。但是按照我在下面使用 php http_build_query 将我的数组转换为查询参数然后将其附加到 url 发送修复它之前的方式构建它。

    try {
    
            // Build a client
            $client = new Client([
                // Base URI is used with relative requests
                'base_uri' => 'https://pro-api.coinmarketcap.com',
                // You can set any number of default request options.
                // 'timeout'  => 2.0,
            ]);
    
            // Prepare a request
            $url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';
            $headers = [
                'Accepts' => 'application/json',
                'X-CMC_PRO_API_KEY' => '05-88df-6f98ba'
            ];
            $params = [
                'id' => '1'
            ];
            $request = new Request('GET', $url.'?'.http_build_query($params), $headers);
    
            // Send a request
            $response = $client->send($request);
    
            // Receive a response
            dd($response->getBody()->getContents());
            return $response->getBody()->getContents();
    
        } catch (\Throwable $th) {
            dd('did not work', $th);
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多