我有一个使用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);
答案 0 :(得分:3)
您需要将查询作为字符串添加到URI。
为此,您可以使用http_build_query或guzzle 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)));
答案 1 :(得分:0)
我也很难弄清楚如何正确放置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;
}