【问题标题】:How to start REST client from zf2 skeleton application如何从 zf2 框架应用程序启动 REST 客户端
【发布时间】:2015-09-04 17:09:39
【问题描述】:

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

客户端必须授权并发送带有新消息的 POST。

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

编辑: 我更仔细地查看了堆栈溢出,发现了一个similar question

现在我的 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();
    }
}

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

【问题讨论】:

    标签: php zend-framework2 skeleton-code


    【解决方案1】:

    Zend 的 Http Client 仅支持基本的HTTP authentication,您可以在发送请求之前轻松地验证您的客户端,如下所示:

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

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

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

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

    【讨论】:

    • 感谢您的参与。你提到的方法我加入了请求,终于奏效了。完成完整查询后,我将把 php 代码放在类似情况下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多