How do I submit POST for cURL in Lithium

一笑奈何 提交于 2019-12-13 02:36:30

问题


I'm trying to create a custom Auth adapter for a legacy API. Let's call the adapter TR42. Right now, I'm debugging TR42::check() so I'm using hardcoded values:

<?php
class TR42 extends \lithium\core\Object {

    public function __construct(array $config = []) {
        $defaults = [
            'scheme' => 'http',
            'host' => 'localhost/tr42/mock_api_authenticate.php',
            'action' => 'authLookup',
            'fields' => ['username', 'password'],
            'method' => 'POST'
        ];
        parent::__construct($config + $defaults);
    }

    public function check($credentials, array $options = []) {
        $postConfig = [
            /**
             * Should I be using 'body' or 'query' to submit POST fields?
             */
            'body' => [
                'username' => 'housni',
                'password' => sha1('legacyHashedPassword'),
                'action' => 'authLookup'
            ],
            'query' => 'username=housni&password=' . sha1('legacyHashedPassword') . '&action=authLookup',
        ];
        $request = new Request($postConfig + $this->_config);

        $stream = new Curl($this->_config);
        $stream->open();
        $stream->write($request);
        $response = $stream->read();
        $stream->close();

        echo '<pre>' . print_r($response, true) . '</pre>';
        die();
    }
}
?>

The file http://localhost/tr42/mock_api_authenticate.php looks like this:

<?php
echo '<h1>This request is: ' . $_SERVER['REQUEST_METHOD'] . '</h1>';
if (!empty($_POST)) {
    echo '<h1>YAY</h1>';
} else {
    echo '<h1>NAY</h1>';
}

echo '<pre>' . print_r($_POST, true) . '</pre>';
?>

Since my cURL code submits a POST request, I'd expect my $_POST to be populated in mock_api_authenticate.php but that's not happening because the output from TR42::check()'s print_r() is:

HTTP/1.1 200 OK
Date: Sun, 18 Aug 2013 04:46:34 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.4.17-1~lucid+1
Vary: Accept-Encoding
Content-Length: 63
Connection: close
Content-Type: text/html

This request is: POST

NAY

Array
(
)

It's saying the request is POST but the POST array (the last empty array) is empty.

What am I doing wrong?

Thanks for reading :)


回答1:


I suggest the use of Lithium Connections and Service classes, to avoid writing your curl request that way.

Extract your legacy api connection configuration (host, port, etc) to a Connection named 'api' or whatever, then, in your adapter's check() body, write something like:

public function check($credentials, array $options = []) {
    return Connections::get('api')->connection->post('/tr42/mock_api_authenticate.php', $credentials);
}


来源:https://stackoverflow.com/questions/18295813/how-do-i-submit-post-for-curl-in-lithium

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!