用curl调用是有效的,而用Guzzle 6调用则不然



我正在尝试将一个有效的代码转换为Guzzle版本,但我没有得到预期的结果,我认为这是由于对Guzzle v6缺乏了解。

如果我执行以下代码,就可以正常工作

$postfields = array(
'identifier' => $this->username,
'secret' => $this->password,
'accesskey' => $this->accesskey,
'action' => 'GetClients',
'responsetype' => self::RESPONSE_TYPE,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url.self::ENDPOINT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);

但如果我尝试转换为Guzzle v6,失败

$client = new GuzzleHttpClient();
$response = $client->post($this->url.self::ENDPOINT, [
'headers' => [
'action' => 'GetClients',
'identifier' => $this->username,
'secret' => $this->password,
'accesskey' => $this->accesskey,
'responsetype' => self::RESPONSE_TYPE
]
]);

我得到一个异常

GuzzleHttpExceptionClientException  : Client error: `GET https://mydomain.test/intranet/includes/api.php` resulted in a `403 Forbidden` response:
result=error;message=Invalid IP 2.137.XXX.XX

另一方面,我不知道如何理解Guzzle客户端的get((方法的调用(形成Guzzle的url(。

理解发送参数的机制时出错,使用headers而不是正确的form_params,因为它是POST方法

正确的代码是

$response = $client->post($this->url.self::ENDPOINT, [
'form_params' => [
'action' => 'GetClients',
'identifier' => $this->username,
'secret' => $this->password,
'accesskey' => $this->accesskey,
'responsetype' => self::RESPONSE_TYPE
]
]);

最新更新