【问题标题】:Using Guzzle to make HTTP requests with GET parameters使用 Guzzle 发出带有 GET 参数的 HTTP 请求
【发布时间】:2018-11-16 03:13:58
【问题描述】:

我正在尝试使用 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"
]);

【问题讨论】:

    标签: php guzzle


    【解决方案1】:

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

    【讨论】:

    • 太棒了!谢谢你这工作!我想我现在要使用 guzzle :)
    • 如果其中一个变量的值包含例如“/”,从而使 URL 无效怎么办?
    • @JarsOfJam-Scheduler 查询字符串与 URL 由 ? 分隔,无论如何,库将对传递给它的变量执行 URL 编码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2018-02-07
    • 2020-11-23
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多