php - 使用 Guzzle 发出带有 GET 参数的 HTTP 请求

标签 php guzzle

我正在尝试使用 Guzzle 从我的服务器发出请求,而不是要求。我使用 cURL 并且有效,但是当我尝试使用 Guzzle 时,我收到一个 403 错误,说客户端拒绝了我的请求,这让我相信参数没有正确传递。

这是我的 cURL 代码:

// Sending Sms
$url = "https://api.xxxxxx.com/v3/messages/send";

$from = "xxxxxx";

$to = $message->getTo();

$client_id = "xxxxxx";

$client_secret = "xxxxxx";

$query_string = "?From=".$from."&To=".$to."&Content=".$content."&ClientId=".$client_id."&ClientSecret=".$client_secret."&RegisteredDelivery=true";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.$query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);

这是我现在的 Guzzle 代码:

$client = new Client();
$response = $client->request('GET', "https://api.xxxxxx.com/v3/messages/send", [
    "From" => "xxxxxx",
    "To" => $message->getTo(),
    "Content" => $content,
    "ClientId" => "xxxxxx",
    "ClientSecret" => "xxxxxx",
    "RegisteredDelivery" => "true"
]);

最佳答案

来自 the documentation :

You can specify the query string parameters using the query request option as an array.

$client->request('GET', 'http://httpbin.org', [
    'query' => ['foo' => 'bar']
]);

所以只需使您的数组成为多维数组,将您的查询字符串参数放在数组的 query 元素中。

$client = new Client();
$response = $client->request('GET', "https://api.xxxxxx.com/v3/messages/send", [
    "query" => [
        "From"               => "xxxxxx",
        "To"                 => $message->getTo(),
        "Content"            => $content,
        "ClientId"           => "xxxxxx",
        "ClientSecret"       => "xxxxxx",
        "RegisteredDelivery" => "true",
    ],
]);

关于php - 使用 Guzzle 发出带有 GET 参数的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326314/

相关文章:

php - 如何使用http客户端laravel上传图片到API

php - 如果与 mysql 或 php 的值相同,则对数据进行分组?

php - Guzzle 返回 500 错误

php mysql 搜索,突出显示包含提供的关键字的部分结果

php - 使用内联编码在输入按键时内联 javascript 警报

php - 使用 Guzzle 进行 OpenSSL 身份验证

php - Composer 自动加载器未加载 GuzzleHttp\ClientInterface

php - 如何将 oAuth 与 Guzzle 5(或者更好的是,与 Guzzle 6)一起使用

php - 如何从 Facebook "like"按钮 JS 代码调用 php 页面?

php - "&reg"被转换为 "®"