Guzzle请求查询参数

6

我有一个使用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);
2个回答

7
你需要将查询作为字符串添加到URI中。为此,你可以使用http_build_queryGuzzle助手函数将参数数组转换为编码的查询字符串:
$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文档让人感到困惑,似乎你可以在$options数组中添加查询参数。 - Elte156

1
我也遇到了如何正确放置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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接