需要为以下curl方法实现Zend_Rest_Client

时间:2012-09-17 12:46:11

标签: php zend-framework curl zend-rest

我通常使用curl来调用rest api,就像这样

$user_data = array("userName" => "myuser@mydomain.com" ,"password" => "mydomain123" );
$data = json_encode($user_data);
$headers = array('Accept: application/json', 'Content-Type: application/json',);
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, 'http://myursl.com/myapi/v1/Api.svc/something/someother');
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
print_r($response);

上面的代码可以正常使用API​​并打印预期的响应,当我使用Zend Framework的Zend_Rest_client做同样的事情

像这样

$base_url = 'http://myursl.com/myapi/v1_0/Api.svc';
$endpoint = '/something/someother';
$user_data = array("userName" => "myuser@mydomain.com" ,"password" => "mydomain123" );
$client = new Zend_Rest_Client($base_url);
$response = $client->restPost($endpoint, $user_data);

我收到404错误

(Zend_Http_Response)#62 (5) { ["version":protected]=> string(3) "1.1" ["code":protected]=> int(404) ["message":protected]=> string(9) "Not Found"] }

实施Zend Rest Client实际上我错了

提前感谢您回复此帖

1 个答案:

答案 0 :(得分:0)

虽然它可能不是最好的解决方案,但最终我最终继承了Zend_Rest_Client并覆盖了_performPost():

class My_Rest_Client extends Zend_Rest_Client {
    protected function _performPost($method, $data = null)
    {
        $client = self::getHttpClient();
        if (is_string($data)) {
            $client->setRawData($data, 'application/json');
        } elseif (is_array($data) || is_object($data)) {
            $client->setParameterPost((array) $data);
        }
        return $client->request($method);
    }
}

然后:

$rest = new My_Rest_Client('http://my.rest.url');
$rest->restPost('post-path', $data);