我正在尝试更新CakePHP 3.5控制器以使用Cake Http Client而不是以下cURL代码:
private function executeRequest($url, $parameters = array(), $http_header, $http_method)
{
$curl_options = array();
switch($http_method){
case self::HTTP_METHOD_GET:
$curl_options[CURLOPT_HTTPGET] = 'true';
if (is_array($parameters) && count($parameters) > 0) {
$url .= '?' . http_build_query($parameters);
} elseif ($parameters) {
$url .= '?' . $parameters;
}
break;
case self:: HTTP_METHOD_POST:
$curl_options[CURLOPT_POST] = '1';
if(is_array($parameters) && count($parameters) > 0){
$body = http_build_query($parameters);
$curl_options[CURLOPT_POSTFIELDS] = $body;
}
break;
default:
break;
}
/**
* An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
*/
if(is_array($http_header)){
$header = array();
foreach($http_header as $key => $value) {
$header[] = "$key: $value";
}
$curl_options[CURLOPT_HTTPHEADER] = $header;
}
$curl_options[CURLOPT_URL] = $url;
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
// Require SSL Certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
//Don't display, save it on result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the Curl Request
$result = curl_exec($ch);
$headerSent = curl_getinfo($ch, CURLINFO_HEADER_OUT );
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ($curl_error = curl_error($ch)) {
throw new Exception($curl_error);
}
else {
$json_decode = json_decode($result, true);
}
curl_close($ch);
return $json_decode;
}
更新的代码是:
private function executeRequest($url, $http_header, $http_method, $parameters = array())
{
$htclient = new Client();
$response = null;
switch($http_method){
case self::HTTP_METHOD_GET:
if (is_array($parameters) && count($parameters) > 0) {
$params = http_build_query($parameters);
} elseif ($parameters) {
$params = $parameters;
}
$response = $htclient->get($url, ['q' => $params], ['headers' => $http_header]);
break;
case self::HTTP_METHOD_POST:
if(is_array($parameters) && count($parameters) > 0){
$response = $htclient->post($url, $parameters, ['headers' => $http_header]);
}
break;
default:
break;
}
return $response->json;
}
当我尝试使用POST
函数时,返回码为error: invalid client
。
POST
的标题是:
$http_header = array(
'Accept' => 'application/json',
'Authorization' => $authorizationHeaderInfo,
'Content-Type' => 'application/x-www-form-urlencoded'
);
,内容数组为:
$parameters = array(
'grant_type' => $grant_type,
'code' => $code,
'redirect_uri' => $redirectUrl
);
这些是cURL
代码中使用的相同数组。
任何想法都会非常感激。
答案 0 :(得分:0)
问题不在CakePHP Client
,我发现在更新过程中我意外更改了调用函数。