如何从 zf2 骨架应用程序启动 REST 客户端


How to start REST client from zf2 skeleton application

简而言之,我想创建一个直接从Zend Framework 2的骨架上使用HTTP基本身份验证的客户端。

客户端必须授权并使用新消息发送 POST。

我从头开始(不完全是 - 我有一个骨架 F2)有人可以向我解释我需要从哪里开始以及如何启动Zend_Rest_Client吗?

编辑:我更仔细地研究了堆栈溢出,发现了一个类似的问题

现在我的 IndexController.php 文件如下所示:

<?php 
namespace Application'Controller;
use Zend'Mvc'Controller'AbstractActionController;
use Zend'View'Model'ViewModel;
use Zend'Http'Request;
use Zend'Http'Client;
use Zend'Stdlib'Parameters;
class IndexController extends AbstractActionController
{
    public function indexAction()
    {
         $request = new Request();
         $request->getHeaders()->addHeaders(array(
           'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
         ));
         $someurl="http://apiurl/public_timeline.json";
         $request->setUri($someurl);
         $request->setMethod('GET');
         $request->setPost(new Parameters(array('page' => 1)));
         $client = new Client();
         $response = $client->dispatch($request);
         $data = json_decode($response->getBody(), true);
         print_r($data);
         return new ViewModel();
    }
}

上面的代码有效,但我想扩展此模块以支持需要身份验证的方法。怎么做?

Zend的Http客户端仅支持基本的HTTP身份验证,您可以在调度请求之前轻松验证客户端,如下所示:

$client = new Client();
$client->setAuth('username', 'password');
$response = $client->dispatch($request);

对于更高级的身份验证机制,如 Oauth2,我强烈建议使用一些第三方 oauth 客户端库,而不是编写自己的客户端库。github上有很多开源和编写良好的Oauth2客户端库。(例如)

当您从远程提供程序获取访问/刷新令牌(或客户端 ID 和密钥)时,只需在请求对象中设置此信息,如下所示:

$request->getHeaders()->addHeaders(array(
    'Accept' => 'application/json',
    'Authorization' => 'Bearer 1234567890abcdefghxxxx', // access token
));
$client = new Client();
$response = $client->dispatch($request);