使用Guzzle使用GET参数发出HTTP请求

时间:2018-11-15 19:04:19

标签: 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"
]);

1 个答案:

答案 0 :(得分:3)

来自the documentation

  

您可以使用query请求选项作为数组来指定查询字符串参数。

$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",
    ],
]);